我试图重载流操作符<<,对于已经有toString()函数返回字符串的类Foo ,使用以下代码:
std::ostream &operator<<( std::ostream &flux, Foo const& foo )
{
flux << foo.toString();
return flux;
}
Run Code Online (Sandbox Code Playgroud)
为了在main.cpp文件中使用它
我的问题是:在哪里放一段代码?
main.cpp它使用之前,它运行良好,但我可能想在其他文件中使用它.如果我把它放入foo.cpp,我得到一个'没有这样的功能'错误:
src/main.cpp:77: error: no match for ‘operator<<’ in ‘std::cout << foo’
Run Code Online (Sandbox Code Playgroud)
这是有道理的,因为代码不包含在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
Run Code Online (Sandbox Code Playgroud)
该foo.h头的确包括在不同的类/文件,但有一个ifdef的后卫,所以我不明白这一点.
那我该怎么办?