c++ - 在哪里放置重载<<code>?

标签 c++ operator-overloading

我正在尝试重载流运算符 <<,对于已经有 toString() 函数返回字符串的 Foo 类,代码如下:

std::ostream &operator<<( std::ostream &flux, Foo const& foo )
{
    flux <<  foo.toString(); 
    return flux;
}

为了在main.cpp文件中使用它

我的问题是:那段代码放在哪里?

  • 如果我将它放在 main.cpp 中,在使用之前,它运行良好,但我可能想在其他文件中使用它。
  • 如果我将它放在 foo.cpp 中,我会收到“没有这样的函数”错误:

    src/main.cpp:77: error: no match for ‘operator<<’ in ‘std::cout << foo’
    

    这是有道理的,因为代码没有包含在 main.cpp 文件中

  • 如果我将它放在类声明之外的 foo.h 类头中,我会收到“多重定义”错误:

    foo.o: In function `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Foo const&)':
    foo.cpp:(.text+0x0): multiple definition of `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Matrix const&)'
    bar.o:bar.cpp:(.text+0x0): first defined here
    

    foo.h 头文件确实包含在不同的类/文件中,但是有一个 ifdef 守卫,所以我不明白这一点。

那我该怎么办呢?

最佳答案

有多种选择:

在header中声明,在Foo之后,在Foo.cpp中定义。

//foo.h
class Foo
{};
std::ostream &operator<<( std::ostream &s, Foo const& foo );

//foo.cpp
#include "foo.h"
std::ostream &operator<<( std::ostream &s, Foo const& foo )
{
    return s;
}

在类定义中将其定义为friend

//Foo.h
class Foo
{
   friend std::ostream &operator<<( std::ostream &s, Foo const& foo )
   {
      return s;
   }
};

将其定义在类定义之外的头文件中,并将其标记为inline以防止重复定义。

//Foo.h
class Foo
{
};

inline std::ostream &operator<<( std::ostream &s, Foo const& foo )
{
   return s;
}

关于c++ - 在哪里放置重载<<code>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13516720/

相关文章:

c++ - 如何使 QList<Type*> 与 indexOf() 和自定义运算符 ==() 一起使用?

c++ - 为什么 auto v {create()};不编译?

c++ - 导出模板代码 = 危险? (MSVC)

c++ - 使用 sc create 启动时 Windows 程序不运行

c++ - 派生重载运算符,但仅对相同类型进行运算

c++ - 为什么忽略 std::optional 的强制转换运算符?

C++ 动态(多阶段)3D vector 实例化和元素分配

c++ - 最佳实践 : A compose B, DerivedA compose DerivedB

具有相同签名的 C++ 模板类运算符重载

c++ - 为什么不能将一个类的常量实例与同一类的非常量实例进行比较?