c++ - 在类中重载 << 运算符

标签 c++ class overloading iostream

我通常将我的类保存在 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/

相关文章:

c++ - 在 C++ 中确定 HID 接口(interface)是 POS 还是键盘

c++ - 为什么 Main 函数上的 Sleep() 会停止所有线程?

java - 对象数组声明

java - 自动装箱和重载

c++ - 打乱矩阵

c++ - Postgres 是否因为 C 的限制而使用内存上下文?

c++ - C++ 中的继承 : define variables in parent-child classes

c++ - 调用基类的 protected 函数时出错

java - 解释在 Kotlin 方法上使用 @JvmOverloads 生成的 Java 代码

java - 过载错误?