重载时未定义的引用错误

时间:2013-11-25 02:57:00

标签: c++ compiler-errors overloading

所以我在这里寻找这个问题的答案,但没有一个解决方案适合我。我已经重载了运算符<<在单独的类“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

还有其他类完美运行。只有当我尝试使用重载的&lt;&lt;而不是toStringFormatted()函数。

所以我的问题是:这里出了什么问题?为什么不定义?而且,最重要的是,我该怎么做才能解决它?

2 个答案:

答案 0 :(得分:1)

你是如何编译的?你编译和链接分开? 您可能会做什么:您通过包含Rolo.h向Main.cpp说有重载运算符。它汇编。但链接器无法找到它的实现。

答案 1 :(得分:0)

在定义函数时,您没有编写运算符的范围。不应该是std::ostream& Rolo::operator <<(std::ostream& outstream, const Rolo& rolo)