[英]Overloading the << operator inside a class
我通常将我的课程保存在2个文件中:class.h和class.cpp
我想做类似cout << myclass的事情;
我发现像这样的例子:
friend ostream& operator<<(ostream &os, XXLint)
{ // do stuff
}
但是上面的函数在声明之后就被显式了。
我应该如何在myclass.h中声明它以便能够在myclass.cpp中使用它? 整个函数的头文件也会位于.cpp文件中(例如:myclass :: myclass())。
在标题的类定义中:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.