您的位置:首页 > 其它

拷贝构造函数在哪些地方用,函数参数,函数返回值

2013-05-24 23:35 302 查看
首先看个程序。

#include <iostream>
using namespace std;

class A
{
public:
	A()
	{
		cout << "A"<<endl;
	}
	~A()
	{
		cout << "~A"<<endl;
	}
private:
	int x;

};

void main()
{
	A a;
	A b(a);
	A c(a);
}


输出结果是:

A

~A

~A

~A

请按任意键继续. . .



=================================================

关于函数参数和函数返回值的构造问题。

函数参数和返回值的构造都是调用的拷贝构造函数。

并且在函数返回时都需要析构。



#include <iostream>
using namespace std;

class A
{
public:
	A()
	{
		cout << "A" <<endl;
	}
	~A()
	{
		cout << "~A" <<endl;
	}
private:
	string x,y;
};

class B : public A
{
public:
	B()
	{
		cout << "B" <<endl;
	}
	~B()
	{
		cout << "~B" <<endl;
	}
private:
	string x1,y1;
};

B fun(B b)
{
	return b;
}

void main()
{
	B a,b;
	b = fun(a);
}

输出结果:

A

B

A

B

~B

~A

~B

~A

~B

~A

~B

~A

请按任意键继续. . .

当把函数调用注释掉后,输出结果是:

A

B

A

B

~B

~A

~B

~A

请按任意键继续. . .



可见相比fun函数的调用,只是多了两次析构函数的调用而已。



#include <iostream>
using namespace std;

class A
{
public:
	A()
	{
		cout << "A" <<endl;
	}
	A(const A &a)
	{
		cout << "construct A" <<endl;
	}
	~A()
	{
		cout << "~A" <<endl;
	}
private:
	string x,y;
};

class B : public A
{
public:
	B()
	{
		cout << "B" <<endl;
	}
	B(const B &a)
	{
		cout << "construct B" <<endl;
	}
	~B()
	{
		cout << "~B" <<endl;
	}
private:
	string x1,y1;
};

B fun(B b)
{
	return b;
}

void main()
{
	B a,b;
	b = fun(a);
}


PS:调用拷贝构造函数之前会自动调用父类的构造函数

A

B

A

B

A

construct B

A

construct B

~B

~A

~B

~A

~B

~A

~B

~A

请按任意键继续. . .



//多余调用的两次析构函数。是函数参数和返回值的析构。

//而函数参数和返回值都是拷贝构造函数完成构造的。

//参考文献:

//http://www.cnblogs.com/renyuan/archive/2012/12/29/2839230.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐