gpt4 book ai didi

c++ - 重载时出现 undefined reference 错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:44:37 26 4
gpt4 key购买 nike

所以我四处寻找这个问题的答案,但没有一个解决方案适合我。我在一个单独的类“Operators.cpp”中重载了运算符<<,具体代码如下:

#include "Rolo.h"
#include "RoloHeader.h"
#include "RoloParsedRecord.h"
#include "RoloRawRecord.h"


std::ostream& operator <<(std::ostream& outstream, const Rolo& rolo){
string roloData = rolo.toString();
outstream << roloData;
return outstream;
}

std::ostream& operator <<(std::ostream& outstream, const RoloHeader& roloHeader){
string roloHeaderData = roloHeader.toString();
outstream << roloHeaderData;
return outstream;
}

std::ostream& operator <<(std::ostream& outstream, const RoloParsedRecord& rpRecord){
string rpRecordData = rpRecord.toString();
outstream << rpRecordData;
return outstream;
}

std::ostream& operator <<(std::ostream& outstream, const RoloRawRecord& rrRecord){
string rrRecordData = rrRecord.toString();
outstream << rrRecordData;
return outstream;
}

在 Rolo.h 中:

friend ostream& operator <<(ostream& outputStream, const Rolo& rolo);
friend ostream& operator <<(ostream& outputStream, const RoloHeader& roloHeader);
friend ostream& operator <<(ostream& outputStream, const RoloParsedRecord& rpRecord);

它在 Main.cpp 中被称为:

Rolo theRolo;
theRolo.readRolo(inStream); //no issues here
theRolo.sortRolo(sortTag); //no issues here either
outStream << theRolo.toStringFormatted(); //prints out exactly as wanted, no issues
outStream << theRolo; //this is where it chokes

当我编译它时,我得到:

Main.o: In function `main':
Main.cpp:(.text.startup+0x3f9): undefined reference to `operator<<(std::ostream&, Rolo&)'
collect2: error: ld returned 1 exit status
make: *** [Aprog] Error 1

还有其他类,运行完美。仅当我尝试使用重载的 << 而不是 toStringFormatted() 函数时才会出现此问题。

所以我的问题是:这里出了什么问题?为什么它是未定义的?而且,最重要的是,我能做些什么来修复它?

最佳答案

你如何编译这个?你编译和链接分开吗?您可能会做什么:您通过包含 Rolo.h 对 Main.cpp 说存在重载运算符。它编译。但是链接器找不到它的实现。

关于c++ - 重载时出现 undefined reference 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20183974/

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