c++虚函数与继承的问题
来源:互联网 发布:js获取页面加载的时间 编辑:程序博客网 时间:2024/06/08 16:12
#include <iostream>using namespace std; class A { protected: int m_data; public: A(int data = 0){m_data = data; } int GetData(){return doGetData();} virtual int doGetData(){ return m_data;/*m_data = 0 */} //接口,如不直接调用,则调用派生类中实现他的函数 }; class B:public A { protected: int m_data; public: B(int data = 1){m_data = data; } //这里 A 中的m_data = 0 ,B中的m_data = 1 int doGetData(){ return m_data ;/*m_data = 1 */} //实现接口 }; class C:public B //C继承了A&B类的方法&属性,且未从新定义接口,故接口还是B类中定义的{ protected: int m_data; public: C(int data = 2){m_data = data; } //这里 A 中的m_data = 0 ,B中的m_data = 1,C 类中的m_data = 2};int main(){C c(10);cout<<c.GetData()<<endl;//本来是要调用C类的GetData(),C中未定义,故调用B中的,但是B中未定义,故调用A中的GetData(),因为A中的doGetData()是虚函数,所以调用//B类中的doGetData(),而B类的doGetData()返回B::m_data,故输出 1cout<<c.A::GetData()<<endl;//因为A中的doGetData()是虚函数,又因为C类中未重定义该接口,所以调用B类中的doGetData(),而B类的doGetData()返回B::m_data,故输出 1cout<<c.B::GetData()<<endl;//肯定返回 1 了cout<<c.C::GetData()<<endl;//因为C类中未重定义GetData(),故调用从B继承来的GetData(),但是B类也未定义,所以调用A中的GetData(),因为A中的doGetData()是虚函数,所以调用B类中的doGetData(),而B类的doGetData()返回B::m_data,故输出 1cout<<c.doGetData()<<endl;//肯定是B类的返回值 1 了cout<<c.A::doGetData()<<endl;//因为直接调用了A的doGetData(),所以输出 0 了cout<<c.B::doGetData()<<endl;//因为直接调用了B的doGetData(),所以输出 1 了cout<<c.C::doGetData()<<endl;//因为C类中未重定义该接口,所以调用B类中的doGetData(),而B类的doGetData()返回B::m_data,故输出 1system("PAUSE");return 0;}
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
原文:http://www.programfan.com/CLUB/showpost.asp?id=21686
- c++虚函数与继承的问题
- 【C++】内联inline、继承、重载与虚函数的解释
- C/C++虚函数与虚继承
- 【继承与多态】C++:继承中的赋值兼容规则,子类的成员函数,虚函数(重写),多态
- 【继承与多态】C++:继承中的赋值兼容规则,子类的成员函数,虚函数(重写),多态
- 友元类与友元函数的继承与传递问题
- 友元类与友元函数的继承与传递问题
- 友元类与友元函数的继承与传递问题
- [C++]虚函数的虚继承
- C++继承、虚继承、虚函数类的大小问题
- C++继承、虚继承、虚函数类的大小问题
- C++继承、虚继承、虚函数类的大小问题
- C++继承、虚继承、虚函数类的大小问题
- C++继承、虚继承、虚函数类的大小问题
- C++继承、虚继承、虚函数类的大小问题
- C++继承、虚继承、虚函数类的大小问题
- C++继承、虚继承、虚函数类的大小问题
- C++继承、虚继承、虚函数类的大小问题
- 隔夜开水不能乱喝啊
- C++文件操作
- EXT Grid控件精华展现 javascript
- jquery checkbox,select,select 取值
- 第八周实验报告1-2
- c++虚函数与继承的问题
- 探秘Java虚拟机——内存管理与垃圾回收
- [Code Sample]Alert "Do you want to save the changes you have made?"
- Why C++ ? 王者归来
- 【零基础学习php一】初识 php
- 编程基础-文字编码-字符集/编码方式/常见乱码错误
- 第八周试探报告1-3
- java中 静态成员、实例成员、构造方法在子类和父类中的执行顺序
- initWithNibName导致的初始化问题