繁体   English   中英

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

[英]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

您有两种选择:

选项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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM