阅读背景:

一个派生的简单例子

来源:互联网 

1、

#include <iostream>
using namespace std;
class A
{
private:
	int x;
protected:
	int y;
public:
	int z;
	void setx(int i)
	{
		x=i;
	}
	int getx()
	{
		return x;
	}
};

class B:public A
{
private:
	int m;
protected:
	int n;
public:
	int p;
	void setvalue(int a,int b,int c,int d,int e,int f)
	{
		setx(a);
		y=b;
		z=c;
		m=d;
		n=e;
		p=f;
	}
	void display()
	{
		cout<<"x="<<getx()<<endl;
//		cout<<"x="<<x<<endl;//基类中x为私有变量,派生类中成员函数不能直接访问
		cout<<"y="<<y<<endl;//基类中y为保护变量,派生类中成员函数可以直接访问
		cout<<"m="<<m<<endl;
		cout<<"n="<<n<<endl;
	}
};

int main()
{
	B obj;
	obj.setvalue(1,2,3,4,5,6);
	obj.display();
	//cout<<"y="<<obj.y<<endl;基类中y为保护变量,派生类的对象不能直接访问
	cout<<"z="<<obj.z<<endl;
	cout<<"p="<<obj.p<<endl;
	return 0;
}#include <iostream>
using namespace std;
c



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: