簡體   English   中英

多態和重載運算符

[英]Polymorphism and overloaded operators

我在繼承的類中玩弄運算符重載。 當我在單個類中定義重載的運算符時,它可以很好地工作(在下面的示例中為+ )。 但是,我無法使其與多態性( [] )一起使用-我收到錯誤消息

main.cpp:70:36: error: ‘int A::operator[]() const’ must take exactly one argument
   virtual int operator[]() const = 0;
                                    ^
main.cpp:80:28: error: ‘int B::operator[]() const’ must take exactly one argument
   virtual int operator[]() const { return b; }
                            ^~~~~
main.cpp: In function ‘int main()’:
main.cpp:90:25: error: expected primary-expression before ‘]’ token
   std::cout << (*a_ptr)[] << "\n";

這是代碼:

#include <iostream>

class A
{
public:
  A(){};
  virtual ~A(){};
  virtual int operator[]() const = 0;
};

class B : public A
{
private:
  int b;

public:
  B(int b_) : b(b_){};
  virtual int operator[]() const { return b; }
  int operator+(const B &rhs) const { return b + rhs.b; }
  int get() { return b; }
};

int main()
{

  ///this gives an error: 
  A *a_ptr = new B(100);
  std::cout << (*a_ptr)[] << "\n";  

  ///this works fine
  B a(10), b(100);
  std::cout << a.get() << "\n";
  std::cout << b.get() << "\n";
  b = a + b;
  std::cout << b.get() << "\n";

  return 0;
}

[] -operator是否特殊,因為它必須只接受一個參數?

根據這個解釋,數組下標運算符必須有一個參數,該參數也由錯誤消息指示; 顯然,數組subsript運算符不可能使用不同的簽名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM