我在重载 <<
时收到警告(尽管有效)上课 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/