如果 不是虚函数,指向子类对象的基类指针只能调用基类的函数,如果是虚函数,就能调用子类的函数。
示例一,非虚函数,指向子类对象的基类指针调用基类函数:
#include <iostream>
using namespace std;
class A{
public:
void fun(){
cout<<"A:fun()"<<endl;
}
};
class B :public A{
public:
void fun(){
cout<<"B:fun()"<<endl;
}
};
int main() {
cout << "hello https://tool.lu/" << endl;
A * pb = new B();
pb->fun();
return 0;
}
结果:
hello https://tool.lu/
A:fun()
示例二,虚函数,指向子类对象的基类指针调用子类函数:
#include <iostream>
using namespace std;
class A{
public:
virtual void fun(){
cout<<"A:fun()"<<endl;
}
};
class B :public A{
public:
void fun(){
cout<<"B:fun()"<<endl;
}
};
int main() {
cout << "hello https://tool.lu/" << endl;
A * pb = new B();
pb->fun();
return 0;
}
结果:
hello https://tool.lu/
B:fun()
网友评论