如何在结构中重载流

How to overload stream in struct

本文关键字:重载 结构      更新时间:2023-10-16

我有一个命名空间需要重载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>添加到标头中,这是一个更细的依赖项。