C++ C++;函数获取特定的函子,但使用基类中的函数 A类{ virtual void operator()(int a,int b){cout
必须继承C++ C++;函数获取特定的函子,但使用基类中的函数 A类{ virtual void operator()(int a,int b){cout,c++,inheritance,parameters,operator-keyword,functor,C++,Inheritance,Parameters,Operator Keyword,Functor,必须继承public才能具有多态性: 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
public
才能具有多态性:
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)
}
此外:
- 您不能在
对象上调用非const
成员函数,因此将const
设置为operator()
const
- 操作员必须是
,而不是公共的
私人的
- 在
中添加main
(不是强制性的,但函数是return
,最好有int main
)return
// .......vvvvvv (omitting `public` means `private` by default
class B : public A {
//...