从基类 (C++) 调用派生类中的非虚函数
Call to non virtual function in derived class from base class (C++)
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;
}
有两种方法可以存档所需的结果:
使用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();
}
};
阅读有关 CRTP 的更多信息。
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 在派生函数中指定void*参数
- 如何通过派生类函数更改基类中的向量
- 如何委托派生类使用其父构造函数?
- 如何使用单独文件中的派生类访问友元函数对象
- 使用基类指针创建对象时,缺少派生类析构函数
- 在 C++ 中用派生类型重写成员函数
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 如果基类包含双指针成员,则派生类的构造函数
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 在派生类中绑定非静态模板化成员函数
- 使用 std::variant<...时调用 BaseState 函数而不是派生函数>
- C++:为什么无法在派生类中访问受保护的构造函数?
- C++派生的类构造函数
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- 覆盖虚拟函数 - 派生类具有不同的参数
- 正在调用基方法,而不是从构造函数派生方法
- 从具有相同虚拟函数的父函数派生时如何调用子函数
- 从派生类对象调用基类函数.派生类构造函数中设置的基类数据成员