您的位置:首页 > 编程语言 > C语言/C++

【C++】派生类对象初始化基类的引用

2015-05-12 21:33 363 查看
//派生类对象初始化基类的引用
//引用是别名,但这个别名只能包含派生类对象中的由基类继承来的隐藏对象

#include <iostream>
using namespace std;
class B
{
public:
B()
{
cout<<"B"<<endl;
}
void fun()
{
cout<<"B::fun()"<<endl;
}
private:
int x;
};

class D : public B
{
public:
D()
{
cout<<"D"<<endl;
}
void fun()
{
cout<<"D::fun()"<<endl;
}
void show()
{
cout<<"D::show()"<<endl;
}
private:
int y;
};
void main()
{
D d;
B &p=d;
p.fun();
//	p.show();          //错误,派生类对象初始化基类的引用不能用于派生类
}
<img src="http://img.blog.csdn.net/20150512213405630?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZG91ZG91d2ExMjM0/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: