构造函数 复制构造函数 类型转换构造函数 析构函数

关于题目中几个构造函数和析构函数的几段程序,主要在于知道什么时候调用各个函数。

程序一:

#include <iostream>
using namespace std;

class Complex{
public:
	double real;
	double imag;

	Complex(double r, double i) 
	{
		real = r;
		imag = i;
		cout << "Construtor 1 called!" << endl;
	}
	//类型转换构造函数
	Complex(int r)
	{
		real = r;
		imag = 0;
		cout << "Construtor 2 called!" << endl;
	}
	//复制构造函数
	Complex(Complex &c)
	{
		real = c.real;
		imag = c.imag;
		cout << "Construtor 3 called!" << endl;
	}
	//析构函数
	~Complex()
	{
		cout << "Desturctor called!" << endl;
	}

};

void Func(Complex c)
{
	
}

Complex Func2()
{
	Complex c(3,4);
	return c;
}

int main()
{
	Complex c1(9, 7);	//1
	Complex c2(c1);		//3
	Complex c3 = c1;	//3
	Complex c4 = 9;	// 2 
	c1 = 5;	//2 d
	Func(c1);	//3 d
	c2 = Func2(); //1 d
	cout << Func2().real << endl;	//1 d
	cout << c1.real << "+" << c1.imag << "i" << endl;
	return 0;
	// d d d d
}

程序二:

/*
会调用几次析构函数?3次!
*/

#include <iostream>
using namespace std;

class A{
public:
	int num;
	A()
	{

	}
	~A()
	{
		cout << "Destructor!" << endl;
	}
};

int main() {

	A * p = new A[2];
	A * p2 = new A;
	A a;
	delete [] p;

}

程序三:


#include<iostream>
using namespace std;

class Demo{
	int id;
public:
	Demo(int i)
	{
		id = i;
		cout << "id=" << id << "constructor" << endl;
	}
	~Demo()
	{
		cout << "id=" << id << "destructor" << endl;
	}
};
Demo d1(1);
void Func()
{
	static Demo d2(2);
	Demo d3(3);
	cout << "Func" << endl;
}
int main()
{
	Demo d4(4);
	d4 = 6;
	cout << "main" << endl;
	{
		Demo d5(5);
	}
	Func();
	cout << "main ends" << endl;
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值