为什么说该代码中哪些类型是远不足的?

发布于 2025-01-30 14:35:12 字数 581 浏览 1 评论 0原文

Tarrayint是Tarray的孩子,为什么我不能在polymorph函数中返回它?

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
};

TArrayInt is a child of TArray, why I can't return it in polymorph functions?

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
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傾旎 2025-02-06 14:35:12

协方差返回类型必须是指示器或参考。您可能希望这些操作员返回参考:

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);
};

Covariant return types must be pointers or references. You probably want those operators to return references:

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);
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文