我正在尝试重载流运算符 <<,对于已经有 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/