我通常将我的类保存在 2 个文件中:class.h 和 class.cpp
我想做一些像 cout << myclass;
我找到了这样的例子:
friend ostream& operator<<(ostream &os, XXLint)
{ // do stuff
}
但是上面的函数在声明之后就被显式化了。
我应该如何在 myclass.h 中声明它以便能够在 myclass.cpp 中使用它?以及整个函数的 header 在 .cpp 文件中的内容(例如:myclass::myclass())。
最佳答案
在 header 中的类定义中:
struct Foo
{
int a, b;
friend std::ostream& operator<<(std::ostream &os, const Foo&);
};
在实现中(例如 .cpp
文件):
std::ostream& operator<<(std::ostream &os, const Foo& f)
{
return os << f.a << " " << f.b;
}
关于c++ - 在类中重载 << 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23184348/