C++ 虚函数 7--在虚函数中使用成员名限定 可以强制解除动态联编

xiaoxiao2021-02-28  28

#include <iostream> #include <string> using namespace std; /*--------------------------------- 13-11在虚函数中使用成员名限定 ---------------------------------*/ class A { public: virtual int get() {return 0;} }; class B:public A { public: int get() {return 1;} }; int main() { B b; A *p=&b; //子类对象赋给基类指针 ,由于父类是个虚函数,故动态联编,调用子类自身的同名函数 cout<<p->get()<<endl; //动态联编, 调用子类的同名函数 cout<<p->A::get()<<endl; //使用成员名限定可以强制解除动态联编, 调用父类的函数 cout<<"-------------"<<endl; B *p1=&b; //子类对象赋给子类自身类型的指针 cout<<p1->get()<<endl; return 0; } 运行结果: 1 0 ------------- 1 Press any key to continue
转载请注明原文地址: https://www.6miu.com/read-1699995.html

最新回复(0)