#include<iostream> #include<string> using namespace std; class Base { public: Base(){} ~Base(){} public: virtual void f1(int x){ cout << "baseclass: f1() " << x << endl; } virtual void f2()final{ cout << "baseclass: f2() " << endl; } void f3(int x){ cout << "baseclass : f3() " <<x<< endl; } virtual void f4(){ cout << "baseclass:f4()" << endl; } //string isbn()const; //virtual double net_price(size_t n)const final; }; class Derive:public Base { public: Derive(){} ~Derive(){} public: //与基类的virtual函数同名不同参数的是重载函数,不能加上override,可以加virtual void f1(double x){ cout << "double derive class :f1()" << x << endl; } //与基类的virtual函数同名同参数的是覆盖函数,可以加virtual,override void f1(int x)override{ cout << "int derived class :f1()" << x << endl; } //基类的f2()加了final,于是去掉注释出错 //void f2()override{ cout << "override derived class: f2() " << endl; } //但是奇怪的来了,与基类的非virtual函数同名同参数的是竟然也是覆盖函数! //如果去掉注释则会输出“"derive class: f3()” //我认为应该产生编译错误,但是却没有 //void f3(int x){ cout << "derive class: f3() " <<x << endl; } //我们看f4()没有任何问题,因为baseclass中声明是virtual,在派生类中会自动把f4()变为virtual void f4(){ cout << "derive class :f4() " << endl; } }; int main() { Base* pBase = new Base(); pBase->f1(1); pBase->f2(); pBase->f3(3); pBase->f4(); cout << endl; Derive* pDerive = new Derive(); pDerive->f1(2.0); pDerive->f1(2); //pDerive->f2(); pDerive->f3(3); pDerive->f4(); cout << endl; return 0; }问题我已经自己解决,原来与virtual函数无关,只是名字冲突与继承的问题。派生类的成员会隐藏同名的基类成员。
C++11 virtual函数学习笔记
最新推荐文章于 2023-10-31 22:13:42 发布