TArrayInt 是 TArray 的子对象,为什么我不能在多态函数中返回它?
template <class T>
class TArray {
public:
virtual T& operator[](int index) = 0;
virtual void push_back(T num) = 0;
virtual TArray operator+=(T num) = 0;
virtual TArray operator+(T num) = 0;
int size();
void print();
};
class TArrayInt :public TArray<int> {
vector<int> array;
public:
int& operator[](int index);
void push_back(int num);
TArrayInt operator+=(int num); //here is an error
TArrayInt operator+(int num); //and here too
};
回答1
协变返回类型必须是指针或引用。您可能希望这些运算符返回引用:
template <class T>
class TArray {
public:
// ...
virtual TArray& operator+=(T num) = 0;
virtual TArray& operator+(T num) = 0;
};
class TArrayInt : public TArray<int> {
public:
// ...
TArrayInt& operator+=(int num);
TArrayInt& operator+(int num);
};