编辑:需要删除帖子——问题微不足道(打字错误),对其他人没有任何帮助
尝试在我的一个 cpp 文件中使用运算符重载时,出现错误 LNK2019,即 Unresolved external 错误。我仔细查看了一下,许多人已经能够通过确保在他们的类原型(prototype)中定义每个方法来解决问题。
老实说,我认为这与我的项目设计有很大关系,但我真的无法准确指出为什么会发生此错误
代码如下:
//a.cpp
//
// ... skipped all code to bottom to where i modified it
//OVERLOADED FUNCTIONS
int operator+(const int n, const a& entry){
return n + entry.getTime();
}
ostream& operator<<(ostream & out, const a& entry){
out << entry.getTitle() << " by " << entry.getArtist()
<< " (" << entry.getTime() << ") ";
return out;
}
//*********************************************************
// a.h
//... only posting what I changed
//
// Inside the class..
class a
{
public:
friend ostream& operator<<(const ostream& out, const a& entry);
friend int operator+(const int n, const a& entry);
//..
//.. SNIPPED
//..
}
当我尝试在 show() 方法中输出一个 b 对象时遇到错误。
//b.cpp
#include "b.h"
b b::etnsl(const int &indexOfItemToAdd) const{
if (originalObjects != NULL && indexOfItemToAdd >= (*originalObjects).size()){
throw "Index out of bounds";
}
b x(originalObjects);
vector<int> *iCopy = x.getIndices();
(*iCopy) = indices;
iCopy->push_back(indexOfItemToAdd);
x.setSum(sum + (*originalObjects)[indexOfItemToAdd].getTime());
return x;
}
void b::show() const{
cout << " Item at loc " << "0x" << this << ":" << endl;
//int j = indices.size();
//if (j == 0)
if (size == 0)
cout << " Empty item." << endl;
else{
for (int i = 0; i < size; i++) //ERROR IN LOOP
cout << " Index " << indices[i] << " : " << (*originalObjects)[indices[i]] << endl;
}
}
int b::getSum() const{
return sum;
}
void b::setSum(const int& num){
sum = num;
}
vector<int>* b::getIndices(){
return &indices;
}
//*********************************************************
//b header class
#ifndef B_H
#define B_H
#include <iostream>
#include <vector>
#include "a.h"
using namespace std;
class b{
private:
int sum, size;
vector <a> *originalObjects;
vector <int> indices;
public:
b(vector<a> *orig = NULL) //counts as 2 constructors: default and a custom one.
: sum(0), originalObjects(orig), size(indices.size()) {
}
b etnsl(const int &indexOfItemToAdd) const;
void show() const;
int getSum() const;
void setSum(const int& num);
vector<int> *getIndices();
};
#endif
最佳答案
ostream& operator<<(ostream & out, const iTunesEntry& tune)
不一样
ostream& operator<<(const ostream& out, const iTunesEntry& entry);
// ~~~~~
在 iTunesEntry 类中(友元方法)
并且不应使用 const
,因为您将不得不修改 ostream
的 out
对象
关于c++ - 运算符重载时出现 Unresolved external 错误,即使在定义了所有方法之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26156228/