c++函数获得特定的函子,但使用基类中的函数

C++ function gets specific functor but uses function from base class

本文关键字:函数 基类 c++      更新时间:2023-10-16
class A {
   virtual void operator()(int a, int b) { cout << a + b << endl; }
};
class B : A {
   void operator()(int a, int b) { cout << a - b << endl; }
};
void f(int a, int b, const A &obj) {
   obj(a, b);
}
int main() {
   int a = 5, b = 3;;
   B obj;
   f(a, b, obj); // should give 2, but gives 8 (uses A's function even if it's virtual)
}

它不使用类B的operator(),而是使用类A的operator()(尽管它被设置为虚函数,所以它应该使用类B的op())。知道怎么修吗?

tl;dr -当我给出从基类继承的特定类的对象作为参数(该类型是最基本类)时,我想使用特定的操作符,而不是基类。

必须继承public才能具有多态性:

// .......vvvvvv (omitting `public` means `private` by default
class B : public A {
//...

:

  • 不能在const对象上调用非const成员函数,所以将operator()设置为const
  • 操作符必须是public,而不是private
  • main中添加return(不是强制性的,但作为功能是int main,最好有return)