C++继承——创建一个含有成员变量的子类对象

定义一个派生类对象(子类)
1、构建所包含的基类(父类)对象:由基类的构造函数完成
2、构建所包含的成员对象:由成员对象类的构造函数完成
3、构建派生类对象:由派生类的构造函数完成
注意:基类对象和成员对象的构造函数所需要的参数需要由派生类对象的构造函数提供

#include <iostream>
using namespace std;

class Base
{
private:
	int a;
public:
	Base() { a = 0; cout << "Default Construct base.\n"; }
	Base(int d) { a = d; cout << "Construct base "<<d<<"\n"; }
	~Base() { cout << "Deconstruct base " << a << endl; }
	void print() { cout << a; }
	int GetA() { return a; }
};

class Derived :public Base
{
private:
	int b;
	Base m;
public:
	Derived() { b = 0; cout << "Default construct Derived.\n"; }
	Derived(int i, int j, int k);
	~Derived() { cout << "Deconstruct Derived " << b << endl; }
	void print() { Base::print(); cout << "," << b << "," << m.GetA() << endl; }
};
// 1、构建所包含的基类(父类)对象,2、构建所包含的成员对象,3、构建派生类对象
// 基类对象和成员对象的构造函数所需要的参数需要由派生类对象的构造函数提供
// 例如下面的 i j 
Derived::Derived(int i, int j, int k) :Base(i), m(j)
{
	b=k
	cout << "Construct Derived.\n";
}

void main()
{
	Derived d[3];
	d[0] = Derived(3, 4, 5);
	d[1] = Derived(7, 8, 9);
	for (int i = 0; i < 2; i++)
		d[i].print();
}

result

posted @ 2019-06-12 11:22  爱做梦的子浩  阅读(384)  评论(0编辑  收藏  举报