为命名空间中的类重载运算符<<时发出警告
warning when overloading operator << for a class within a namespace
当命名空间Shape
中Rectangle
类重载<<
时,我会收到警告(尽管它有效(。请注意,我使用 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);
};
}
只需删除Shape::
:
std::ostream& operator<<(std::ostream &os, const Rectangle &rectangle) {
os << "rectangle";
return os;
}
编辑:您还必须将重载的函数定义封装在namespace Shape {...}
中。
或者,您可以在 namespace Shape
内声明operator<<()
,但在Rectangle
外部声明:
namespace Shape {
class Rectangle {
public:
friend std::ostream &operator<<(std::ostream &os, const Rectangle &rectangle);
};
std::ostream &operator<<(std::ostream &os, const Rectangle &rectangle);
}
相关文章:
- 警告处理为错误这里有什么问题
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- cppcheck在const std::string[]上引发警告
- GCC对可能有效的代码抛出init list生存期警告
- 如何在BST的这个简单递归实现中消除警告
- 关于std::move的使用,是否有编译警告
- g++ 在某个类成员未初始化时不发出警告
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- 如何处理来自核心指南检查器的关于gsl::at的静态分析警告
- 使用typeid警告未使用的变量
- 示例C++项目编译中的警告
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 如何修复编译器警告 C6386 和 C6385?
- 返回语句后的代码,没有警告
- 获取隐式转换溢出从无符号到已签名的警告
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型