本文主要是介绍记录C++的类中,如果不写virtual,子类不会覆盖父类同名函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
直接放代码:
#include <iostream>
using namespace std;class AAA {
public:AAA() {}~AAA() {}void func() {YourVar = 20;}void print() {cout << "YourVar: " << YourVar << endl;}public:int YourVar = 10;};class BBB : public AAA {
public:BBB() {YourVar = 20;}~BBB() {}void print() {cout << "*********************"<< endl;cout << "YourVar: " << YourVar << endl;cout << "********************" << endl;cout << endl;}//private:
// int YourVar;
};int main() {BBB *b = new BBB;b->print();AAA *a = (AAA*)b;a->print();return 0;
}
运行结果:
发现,子类重新了同名函数print,并没有覆盖父类的函数,于是我试试添加virtual 关键字:
#include <iostream>
using namespace std;class AAA {
public:AAA() {}~AAA() {}void func() {YourVar = 20;}virtual void print() {cout << "YourVar: " << YourVar << endl;}public:int YourVar = 10;};class BBB : public AAA {
public:BBB() {YourVar = 20;}~BBB() {}void print() {cout << "*********************"<< endl;cout << "YourVar: " << YourVar << endl;cout << "********************" << endl;cout << endl;}//private:
// int YourVar;
};int main() {BBB *b = new BBB;b->print();AAA *a = (AAA*)b;a->print();return 0;
}
注意:
当然了,这里BBB的print函数后面虽然不加override也行,但是规范的话,其实应该加override关键字修饰!!!
结论:
1. 这里是我基础有待完善,virtual 关键字的函数才会被覆盖
这篇关于记录C++的类中,如果不写virtual,子类不会覆盖父类同名函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!