C++.继承.基类和派生类

113 阅读1分钟
#include<iostream>
using namespace std;
class A
{
public:A() { x = 1; }
	  int out() { return x; }
	  void addX() { x++; }
private:int x;
};
class B:public A                            //私有数据成员的测试
{
public:B() { y = 1; }
	  int out() { return y; }
	  void addY() { y++; }
private:int y;
};
int main()
{
	A a;
	cout << "a.x=" << a.out() << endl;//调用构造函数对数据进行赋值
	B b;//基类的私有数据成员 不能在派生类中直接访问 但派生类对象建立私有数据空间  创建派生类对象 调用基类 派生类构造函数
	b.addX(); b.addY();//调用基类公有成员函数
	cout << "b.x=" << b. A::out() << endl;//调用基类版本同名函数 返回b.x的值
	cout << "b.y=" << b. out()<< endl;
}