c++函数获得特定的函子,但使用基类中的函数
C++ function gets specific functor but uses function from base class
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
)
相关文章:
- 基类中的函数名称解析
- 如何通过派生类函数更改基类中的向量
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如果基类包含双指针成员,则派生类的构造函数
- C++ 继承:将子类传递给需要基类的函数并获取子类行为
- 继承和友元函数,从基类访问受保护的成员
- 使用子类覆盖基类中定义的函数
- 如何基于模板化类的基类专门化成员函数
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- 使用基类指针调用基类的值构造函数的语法是什么?
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 如何在基类指针向量的元素上应用重载的多态函数
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 被覆盖的函数不会反映在基类中,这是正常行为吗?
- 在初始化列表之外手动调用基类的构造函数
- 重写打印函数而不是覆盖基类
- C++17 使用驱动类常量作为基类构造函数的参数来初始化基类构造函数
- C++虚拟函数:基类函数是调用的,而不是派生的
- 虚拟函数-基类指针