【发布时间】:2012-11-22 16:24:08
【问题描述】:
我正在尝试重载流运算符 toString() 函数返回字符串的类 Foo,使用以下代码:
std::ostream &operator<<( std::ostream &flux, Foo const& foo )
{
flux << foo.toString();
return flux;
}
为了在main.cppfile 中使用它
我的问题是:把那段代码放在哪里?
- 如果我将它放在
main.cpp中,在它使用之前它运行良好,但我可能想在其他文件中使用它。 -
如果我将它放在
foo.cpp中,我会收到“没有这样的功能”错误:src/main.cpp:77: error: no match for ‘operator<<’ in ‘std::cout << foo’这是有道理的,因为代码不包含在
main.cpp文件中 -
如果我将它放在
foo.hclass 标头中,在类声明之外,我会收到“多重定义”错误: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 herefoo.h标头确实包含在不同的类/文件中,但是有一个 ifdef 保护,所以我不明白这一点。
那我该怎么办?
【问题讨论】: