subset
不是虚函数,并且在基类和派生类中均定义。
我有一个派生类对象。最终调用基类的test
而不是派生类中的test
。
为什么会这样呢?
如何设置它,以便根据对象类型调用测试。
当前o / p
B func
A f1
A test
我希望它成为
B func
A f1
B test
#include <iostream>
using namespace std;
class A {
protected:
void test()
{
cout<<"A test"<<endl;
}
void f1(){
cout<<"A f1" <<endl;
test();
}
};
class B: public A {
protected:
void test()
{
cout<<"B test" <<endl;
}
public:
void func(){
cout<<"B func" << endl;
f1();
}
};
int main()
{
B tmp;
tmp.func();
return 0;
}
答案 0 :(得分:1)
有两种方法可以归档所需的结果:
使用virtual
将基类函数声明为虚函数将确保默认情况下调用目标函数的最高继承。例如,在您的情况下:
class A {
protected:
/**
* Declared also in the derived class, so as long the current object is the derived class,
* this function will be called from the derived class.
* [Enabled only due to the use of the `virtual` keyword].
*/
virtual void test() {
cout << "A test" << endl;
}
void f1() {
cout << "A f1" << endl;
test();
}
};
使用CRTP [大量的存档内容,您可以使用虚拟存档的内容]
template <class Derived> // Template param that will accept the derived class that inherit from this class.
class A {
protected:
virtual void test() const {
cout << "A test" << endl;
}
void f1() const {
cout << "A f1" << endl;
static_cast<Derived const&>(*this).test(); // Call test() function from the derived class.
}
};
class B: public A<B> { // inherit A that accepts template argument this derived class
// protected:
public: // Pay attention that now test should be public in the derived class in order to access it via the base class.
void test() const override {
cout << "B test" << endl;
}
//public:
void func() const {
cout << "B func" << endl;
f1();
}
};