0

所以我有以下简单的代码

#include <iostream>

class Base {
public:
  virtual int GetX() const = 0;
  virtual int GetY() const = 0; 
  virtual Base& operator=(const Base&) = 0;
protected:
  int x;

};

class Derived : public Base {
public:
  Derived(int a = 0, int b = 0):y(b){x=a;};
  Base& operator=(const Base&);

  int GetX() const{return x;}
  int GetY() const{return y;}
  void Print(){std::cout << x << y << std::endl;}
private:
  int y;
};

Base& Derived::operator=(const Base& t)
{
  y = t.GetY();
  x = t.GetX();
  return *this;
}

int main()
{
  Derived A(1,2);
  Derived B;
  B = A;
  A.Print();
}

我的问题是运算符 = 的定义,因为我收到以下错误,除非我注释 B=A 行:

In function `Derived::operator=(Derived const&)':
File.C:(.text._ZN7DerivedaSERKS_[_ZN7DerivedaSERKS_]+0x1f): undefined reference to `Base::operator=(Base const&)'
collect2: error: ld returned 1 exit status

我已经尝试了许多有关复制分配的解决方法,但没有任何效果。我需要在基类中定义它,因为我需要另一个派生类(派生2),理想情况下我什至能够在派生类之间相等。

编辑:粘贴错误的代码

4

1 回答 1

1

因为你没有实现Derived::operator=(Derived const &),编译器给你一个默认的调用Base::operator=(Base const &),它不存在。

如果您想编译和链接,Derived::operator=(Derived const &)您必须实现其中一个。Base::operator=(Base const &)B = A

你可以做到B = static_cast <Base const&> (A);

于 2014-10-24T00:09:58.320 回答