1

在下面的代码中,在派生类上调用operator()withint不会编译,但是,在派生类上调用get()with intordouble可以正常工作。

with input 和operator()都只在基类中实现,而不在派生类中实现。intget()

保留或删除 virtual 关键字不会影响结果。

class A {
public:
  virtual double operator()(double& x) { return 0; }
  virtual int operator()(int& i) { return 1; }
  virtual double get(double& x) { return 2; }
  virtual int get(int& i) { return 3; }
};

class B : public A {
public:
  double operator()(double& x) { return 4; }
};

int main() {

  B b;
  A& a = *(&b);

  double x = 100.0;
  int i = 1;

  std::cout << a(x) << "\n";
  std::cout << b(x) << "\n";
  std::cout << a(i) << "\n";
  std::cout << "b(i)" << "\n"; // this line does not compile when it is b(i) instead of "b(i)" 
  std::cout << a.get(x) << "\n";
  std::cout << b.get(x) << "\n";
  std::cout << a.get(i) << "\n";
  std::cout << b.get(i) << "\n";

}

运算符方法与导致此问题的其他方法之间是否存在根本区别?

4

0 回答 0