简体   繁体   English

重载类中的<<操作符

[英]Overloading the << operator inside a class

I usually keep my classes in 2 files : class.h and class.cpp 我通常将我的课程保存在2个文件中:class.h和class.cpp

I want to do something like cout << myclass; 我想做类似cout << myclass的事情;

I have found examples like : 我发现像这样的例子:

friend ostream& operator<<(ostream &os, XXLint)
{ // do stuff
}

But the above function gets explicited right after the declaration. 但是上面的函数在声明之后就被显式了。

How should I declare it in myclass.h in order to be able to use it in myclass.cpp ? 我应该如何在myclass.h中声明它以便能够在myclass.cpp中使用它? And also what would the entire function's header be in the .cpp file ( eg : myclass::myclass() ). 整个函数的头文件也会位于.cpp文件中(例如:myclass :: myclass())。

In the class definition in the header: 在标题的类定义中:

struct Foo
{
  int a, b;
  friend std::ostream& operator<<(std::ostream &os, const Foo&);
};

In an implementation (eg .cpp file): 在实现中(例如.cpp文件):

std::ostream& operator<<(std::ostream &os, const Foo& f)
{
  return os << f.a << " " << f.b;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM