C++学习日志35-----基类默认构造函数、构造与析构


一、基类默认构造函数

#include<iostream>
using std::cout;
using std::endl;
//任务:基类默认构造函数的使用
//B:public ;

class A
{
    
    
	//base class
public:
	A() = default;
	A(int i) {
    
     cout << "A(" << i << ")" << endl; }
};

class B :public A
{
    
    
public:
	B() {
    
     cout << "B()" << endl; }
	B(int j) :A(j) {
    
     cout << "B(" << j << ")" << endl; }
};

int main()
{
    
    
	A a1();
	A a2{
    
     1 };
	B b1{
    
    };
	B b2{
    
     2 };
	std::cin.get();


}

在这里插入图片描述
结果如上图所示。

二、构造与析构

//任务1:创建类结构:Computer->PC->Desktop/Laptop以及相应的ctor/dtor
//main中创建Desktop/laptop的对象,观察ctor/dtor调用次序

//任务2:增加类Camera作为Laptop的内嵌对象c的类型
//main中创建Laptop对象,观察内嵌对象c的构造与基类构造次序
#include<iostream>
using std::cout;
using std::endl;
class Computer
{
    
    
public:
	Computer() {
    
     cout << "Computer" << endl; }
	~Computer() {
    
     cout << "~Computer" << endl; }
};
class PC :public Computer
{
    
    
public:
	PC() {
    
     cout << "PC()" << endl; }
	~PC() {
    
     cout << "~pc()" << endl; }
};
class Desktop :public PC
{
    
    
public:
	Desktop() {
    
     cout << "Desktop()" << endl; }
	~Desktop(){
    
     cout << "~Desktop" << endl; }
};
class Camera
{
    
    
public:
	Camera() {
    
     cout << "Embeddded Camera()" << endl; }
	~Camera() {
    
     cout << "Embeddded ~Camera()" << endl; }
};
class Laptop :public PC
{
    
    
private:
	Camera c{
    
    };
public:
	Laptop() {
    
     cout << "Laptop()" << endl; }
	~Laptop() {
    
     cout << "~Laptop()" << endl; }
};
int main()
{
    
    
	{
    
    
		Desktop d{
    
    };
		Laptop l{
    
    };
	}
}

在这里插入图片描述
结果如上图所示。

猜你喜欢

转载自blog.csdn.net/taiyuezyh/article/details/124271498
今日推荐