即使在定义了所有方法之后,在操作符重载时也会得到未解决的外部错误

时间:2014-10-02 07:36:08

标签: c++ unresolved-external

编辑:需要删除帖子 - 问题很简单(印刷错误)并且不会对他人有任何帮助

当我尝试在我的一个cpp文件中使用运算符重载时,我得到了errorLNK2019,这是一个未解决的外部错误。我看了一遍,许多人已经能够通过确保在他们的类原型中定义每个方法来解决问题。

我认为这对我的项目设计要做的很多,说实话,但我真的无法准确找出错误发生的原因

以下是代码:

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

1 个答案:

答案 0 :(得分:2)

ostream& operator<<(ostream & out, const iTunesEntry& tune)

不同
ostream& operator<<(const ostream& out, const iTunesEntry& entry);
//                  ~~~~~

在iTunesEntry类中(朋友方法)

并且const不应该被使用,因为您必须修改out的{​​{1}}对象