#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; } //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; } }; int main() { Base* pBase = new Base(); pBase->f1(1); pBase->f2(); pBase->f3(3); cout << endl; Derive* pDerive = new Derive(); pDerive->f1(2.0); pDerive->f1(2); //pDerive->f2(); pDerive->f3(3); cout << endl; return 0; }
C++11 virtual函数学习笔记,布布扣,bubuko.com
原文地址:http://blog.csdn.net/u014120684/article/details/25842343