我想重载我自己的结构<<
运算符,保存在自己的.hpp
文件中,如下所示:
#ifndef MY_STRUCTS_HPP
#define MY_STRUCTS_HPP
#include <iostream>
#include <string>
typedef struct {
std::string a;
std::string b;
} Info;
std::ostream &operator<<(std::ostream &o, const Info &rhs) {
o << "Name: " << rhs.a << "\t" << rhs.b;
return o;
}
#endif
这是我的主文件的样子:
#include "InfoBuilder.hpp"
#include "myStructs.hpp"
#include <iostream>
// Overloading the operator exactly the same, but here works
// std::ostream &operator<<(std::ostream &o, const Info &rhs) {
// o << "Name: " << rhs.a << "\t" << rhs.b;
// return o;
// }
int main(){
InfoBuilder s();
std::cout << s.getArtistInfo("architects") << std::endl;
return 0;
}
编译它会出现此错误:
CMakeFiles/foo.dir/src/InfoBuilder.cpp.o: In function `operator<<(std::ostream&, Info const&)':
InfoBuilder.cpp:(.text+0x159): multiple definition of `operator<<(std::ostream&, Info const&)'
CMakeFiles/foo.dir/src/main.cpp.o:main.cpp:(.text+0xa4): first defined here
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/foo.dir/build.make:126: foo] Error 1
make[1]: *** [CMakeFiles/Makefile2:68: CMakeFiles/foo.dir/all] Error 2
make: *** [Makefile:84: all] Error 2
在myStructs.hpp
文件中注释重载的运算符,只在main.cpp
文件中定义它。但是,为什么这会产生影响因为我使用包含警卫?
我还在myStructs.hpp
中添加了InfoBuilder.hpp
。
答案 0 :(得分:1)
您有两种选择:
<强> myStructs.hpp 强>
#include <iostream>
#include <string>
#include "myStructs.hpp"
std::ostream &operator<<(std::ostream &o, const Info &rhs) {
o << "Name: " << rhs.a << "\t" << rhs.b;
return o;
}
<强> myStructs.cpp 强>
#ifndef MY_STRUCTS_HPP
#define MY_STRUCTS_HPP
#include <iostream>
#include <string>
typedef struct {
std::string a;
std::string b;
} Info;
static std::ostream &operator<<(std::ostream &o, const Info &rhs) {
o << "Name: " << rhs.a << "\t" << rhs.b;
return o;
}
#endif
<强> myStructs.hpp 强>
{{1}}