如何在结构中重载流
How to overload stream in struct
我有一个命名空间需要重载ostream进行编译,当我在结构中添加时,它抱怨两个参数,只有一个允许,当我在结构之后添加时,仍然没有编译:
namespace ORT {
struct MimeType {
MimeType(const std::string & type = "")
: type(type)
{
}
std::string toString() const { return std::string(type); }
std::string type;
};
std::ostream& operator<< (std::ostream& stream, const MimeType& mt) {
std::cout << mt.type;
return stream;
}
...
它说:在函数ORT::operator<<(std::basic_ostream<char, std::char_traits<char> >&, ORT::MimeType const&)':
/ort.h:56: multiple definition of
ORT::operator<<(std::basic_ostream>&, ORT::MimeType const&)'收集2:LD 返回 1 个退出状态make: *** [build/x86_64/bin/libopenrtb.3da2981d03414ced8d640e67111278c1.so] 错误 1
但我只包括 ostream,没有多个实例。当我只放:
它说:错误:"结构"之前的预期初始值设定项错误:预期在输入末尾制造:*** 错误 1
发生这种情况是因为您在头文件中定义了一个未标记为inline
的函数。 将operator <<
的定义移动到相应的.cpp文件,或添加 inline
关键字:
inline std::ostream& operator<< // ...
就个人而言,我会将其移动到.cpp文件中。 然后,您也可以将标头中的#include <iostream>
移动到.cpp文件中,并将#include <iosfwd>
添加到标头中,这是一个更细的依赖项。
相关文章:
- 在哪里声明结构运算符重载
- 为私有结构定义双参数运算符重载
- 重载嵌套结构/类的流插入运算符
- 逗号在重载 ostream 和 istream 在结构中分开
- 重载运算符>>() 表示未知的输入长度/结构
- 类层次结构中的运算符重载
- 为什么我应该重载 () 运算符以在结构而不是类中priority_queue?
- 具有重载方法的可变参数数据结构
- std::cout 不适用于结构的重载"<<"运算符
- 为什么C++在自定义结构向量时会出现 ostream 重载问题?
- Ho 在标头中声明是结构中的重载运算符?
- 指向结构的指针的运算符重载
- 结构外部的重载运算符
- 无法使用"enable_if"和"is_base_of"将模板函数"operator+"的重载限制到我的类层次结构
- 菱形层次结构中的虚函数重载在 clang 和 gcc 中产生不同的结果
- 如何重载结构的空运算符
- 如何重载结构向量的<<
- C++ 运算符<重载结构
- c++运算符+=重载结构字符串
- 如何正确重载结构'+'运算符