gpt4 book ai didi

c++ - 重载运算符 << 时出现链接错误

转载 作者:行者123 更新时间:2023-11-28 05:01:34 26 4
gpt4 key购买 nike

我想重载 <<我自己的结构的运算符保存在它自己的 .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 中注释掉重载运算 rune 件并在 main.cpp 中定义它文件有效。但是为什么这会在我使用 include guards 时产生影响呢?我还包括 myStructs.hppInfoBuilder.hpp .

最佳答案

你有两个选择:

选项 1:将函数的实现放在 cc 文件中:

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;
}

选项 2:将函数标记为静态

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

关于c++ - 重载运算符 << 时出现链接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45786499/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com