重载运算符时的链接错误<<

时间:2017-08-20 20:27:39

标签: c++ struct include operator-overloading

我想重载我自己的结构<<运算符,保存在自己的.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

1 个答案:

答案 0 :(得分:1)

您有两种选择:

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

<强> 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

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

<强> myStructs.hpp

{{1}}