gpt4 book ai didi

c++ - 为命名空间中的类重载运算符 << 时发出警告

转载 作者:行者123 更新时间:2023-11-30 05:05:19 25 4
gpt4 key购买 nike

我在重载 << 时收到警告(尽管有效)上课 Rectangle在命名空间 Shape .请注意,我使用 Clion 生成了过载,但仍然收到警告。

矩形.h

#include <ostream>

namespace Shape {

class Rectangle {
public:
friend std::ostream &operator<<(std::ostream &os, const Rectangle &rectangle);
};
}

矩形.cpp

#include "Rectangle.h"

using namespace Shape;

std::ostream& Shape::operator<<(std::ostream &os, const Rectangle &rectangle) {
os << "rectangle";
return os;
}

警告:

warning: 'std::ostream& Shape::operator<<(std::ostream&, const Shape::Rectangle&)' has not been declared within Shape
std::ostream& Shape::operator<<(std::ostream &os, const Rectangle &rectangle) {
^~~~~

note: only here as a friend
friend std::ostream &operator<<(std::ostream &os, const Rectangle &rectangle);
^~~~~~~~

如何正确地做到这一点,这样我就不会收到警告?谢谢

最佳答案

我找到了!

您必须在命名空间中定义重载方法,而不是在类中。

#include <ostream>

namespace Shape {

class Rectangle {
};
std::ostream &operator<<(std::ostream &os, const Rectangle &rectangle);
}

不是这样的:

#include <ostream>

namespace Shape {

class Rectangle {
public:
friend std::ostream &operator<<(std::ostream &os, const Rectangle &rectangle);
};
}

关于c++ - 为命名空间中的类重载运算符 << 时发出警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48452968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com