#include<iostream>
using namespace std;
class Father{
public:
int getNum(){
return 1;
}
private:
int Num;
};
class Child:public Father{
public:
int getNum(){
return Num;
}
int static const Num = 10;
};
int main(){
int i=0;
int j = 0;
Father *father = new Child();
Father *father1 = new Father();
//Child *child1 = new Father();
<
using namespace std;
class Father{
public:
int getNum(){
return 1;
}
private:
int Num;
};
class Child:public Father{
public:
int getNum(){
return Num;
}
int static const Num = 10;
};
int main(){
int i=0;
int j = 0;
Father *father = new Child();
Father *father1 = new Father();
//Child *child1 = new Father();
<

本文探讨了C++中父类和子类方法调用的情况,通过示例展示了虚拟函数(virtual)在多态中的作用。当使用父类指针调用子类的成员函数时,虚拟函数实现动态绑定,使得调用正确地指向子类的方法。然而,尝试将父类指针赋值给子类指针,即使方法声明为virtual,也会导致编译错误。
最低0.47元/天 解锁文章

3254

被折叠的 条评论
为什么被折叠?



