我正在尝试重载流运算符 toString()函数返回一个字符串,代码如下:
std::ostream &operator<<( std::ostream &flux, Foo const& foo )
{
flux << foo.toString();
return flux;
}
为了在一个main.cpp
file
我的问题是:那段代码放在哪里?
- 如果我把它放在
main.cpp
,在使用之前,它运行良好,但我可能想在其他文件中使用它。
-
如果我把它放在foo.cpp
,我收到“没有此类功能”错误:
src/main.cpp:77: error: no match for ‘operator<<’ in ‘std::cout << foo’
这是有道理的,因为代码不包含在main.cpp
file
-
如果我把它放在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
The foo.h
header 确实包含在不同的类/文件中,但是有一个 ifdef 保护,所以我不明白这一点。
那么我该怎么办呢?
有多种选择:
在标题中声明它,之后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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)