首页 > 代码库 > C++11 virtual函数学习笔记
C++11 virtual函数学习笔记
#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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。