注意以下都是讨论public:
C++派生类可以访问基类成员函数,但是想让基类访问派生类应该怎么做?
如下:
#include <iostream>
#include <memory>
class Base{
public:
Base(){}
~Base(){}
virtual void print() = 0;
};
class NextBase : public Base//, public Base1
{
public:
NextBase(){}
void PrintNextBase(){
std::cout << "print next base" << std::endl;
}
virtual void print1() = 0;
};
class Application : public NextBase{
public:
Application(){}
virtual void print() override{
std::cout << "Application come next base" << std::endl;
}
virtual void print1() override{
std::cout << "Application come application" << std::endl;
}
void print2(){
std::cout << "2Application come application" << std::endl;
}
};
如下代码就会报错:
Base* ptrBase = new Application();
ptrBase->PrintNextBase();
如下代码就不会报错:
Base* ptrBase = new Application(); //std::make_shared<Application>();
((Application *)ptrBase)->print2();