派生类的构造和析构

派生类构造函数名(总参数表列) :基类构造函数名(参数表列){派生类中新增数据成员初始化语句}

先调用基类的构造函数,再调用派生类的构造函数。析构顺序与构造顺序相反。

在类中对派生类的构造函数作声明时,不包括基类构造函数名及其参数表列,只有在定义的时候给出。

#include <iostream>
using namespace std;

class parent {
public:
	parent(int a, int b) {
		this->a = a;
		this->b = b;
		cout << "父类构造函数" << endl;
	}
	~parent() {
		cout << "父类析构函数" << endl;
	}
private:
	int a;
	int b;
};

class child :public parent {
public:
	child(int a,int b,int c);
	~child() {
		cout << "子类析构函数" << endl;
	}
private:
	int c;
};
child::child(int a, int b, int c):parent(a,b) {
		this->c = c;
		cout << "子类构造函数" << endl;
}

void display_obj() {
	child b(1, 2, 3);
}
int main() {
	display_obj();

}

包含子对象的派生类的构造函数:

先调用基类构造函数,然后调用子对象的构造函数,最后调用派生类的构造函数。析构顺序与构造顺序相反。

对于这种形式的派生类构造函数一般形式:

派生类构造函数名(总参数表列):基类构造函数名(参数表列),子对象名(参数表列){派生类中新增成员}

#include <iostream>
using namespace std;

class A {
public:
	A(int a){
		this->a = a;
		cout << "A的构造函数" << endl;
	}
	~A() {
		cout << "A的析构函数" << endl;
	}
private:
	int a;
};

class parent {
public:
	parent(int a, int b) {
		this->a = a;
		this->b = b;
		cout << "父类构造函数" << endl;
	}
	~parent() {
		cout << "父类析构函数" << endl;
	}
private:
	int a;
	int b;
};

class child :public parent {
public:
	child(int a,int b,int c,int d);
	~child() {
		cout << "子类析构函数" << endl;
	}
private:
	int c;
	A a1;
};
child::child(int a, int b, int c,int d):parent(a,b),a1(d) {
		this->c = c;
		cout << "子类构造函数" << endl;
}

void display_obj() {
	child b(1, 2, 3,4);
}
int main() {
	display_obj();

}

当不需要对派生类新增成员进行任何初始化操作时,派生类构造函数的函数体可以为空,这种构造函数的作用只是为了将参数传递给基类构造函数和子对象。

当子类的成员变量和父类的成员变量同名时,仍然继承父类的成员变量,使用作用域限定符显式进行区分;同名成员函数同理。

#include <iostream>
using namespace std;

class A {
public:
	A(int a, int b) {
		this->a = a;
		this->b = b;
	}
protected:
	int a;
	int b;
};
class B:public A {
public:
	B(int b,int c,int d):A(c,d) {
		this->b = b;
	}
public:
	void print() {
		cout << A::b << endl; //访问基类的同名成员变量,通过作用域限定符
		cout << b << endl;  //子类中的变量
	}
private:
	int b;
};

int main() {
	B b(1, 2, 3);
	b.print();
    b.A::print(); //访问A类的成员函数
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/aabb7012086/article/details/81197553