[英]Linking error when overloading operator <<
我想为保存在其自己的.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
文件中myStructs.hpp
重载的运算符,然后在main.cpp
文件中对其进行定义即可。 但是,为什么在使用包含防护时会有所不同? 我还在myStructs.hpp
中包含InfoBuilder.hpp
。
您有两种选择:
myStructs.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);
#endif
myStructs.cpp
#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.hpp
#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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.