C++中的拷贝构造的几种用法

一、基本概念:

1、用一个类的对象初始化该类的另一个对象被称为缺省按成员初始化,在概念上,一个类的对象向该类的另一个对象作拷贝是通过调用拷贝构造函数实现的,而拷贝构造函数由编译器提供,并依次拷贝每个非静态数据成员来实现。类的设计者也可以通过提供特殊的拷贝构造函数来改变缺省的行为,如果定义了拷贝构造函数,则在用一个类的对象初始化该类另一个对象时它就会被调用。

2、本质上还是一个构造函数,只是函数的参数,是一个本类类型的对象
二、第一种用法 A a2 = a1;

#include <iostream>

using namespace std;

class A
{
public:
	A()
	{
		cout << "我是构造函数,自动被调用了" << endl;
	}
	A(const A &obj)
	{
		cout << "我也是构造函数,我是通过另一个对象来初始化我自己" << endl;
	}
	~A()
	{
		cout << "我是析构函数,自动被调用了" << endl;
	}
private:
	int a;
};

int main()
{
	A a1;
	A a2 = a1;
	system("pause");
	return 0;
}

运行结果:

注意:A a2 = a1;与a2=a1;是不同的,后者是用a1来=号给a2,是编译器给我们提供的浅拷贝。

三、第二种用法 A a2(a1);

#include <iostream>

using namespace std;

class A
{
public:
	A()
	{
		cout << "我是构造函数,自动被调用了" << endl;
	}
	A(int _a)
	{
		a = _a;
	}
	A(const A &obj)
	{
		a = obj.a;
		cout << "我也是构造函数,我是通过另一个对象来初始化我自己" << endl;
	}
	~A()
	{
		cout << "我是析构函数,自动被调用了" << endl;
	}
	void getA()
	{
		cout << "a=" << a << endl;
	}
private:
	int a;
};

int main()
{
	A a1(10);
	A a2(a1);
	a2.getA();
	system("pause");
	return 0;
}

运行结果:


四、第三种用法,当函数的形参是对象时,会调用拷贝构造函数来进行形参的初始化

#include "iostream"
using namespace std;


class Point
{
public:
	Point(int xx = 0, int yy = 0)
	{
		X = xx;  Y = yy;  cout << "Constructor Object.\n";
	}
	Point(const Point & p) 	    //复制构造函数
	{
		X = p.X;  Y = p.Y;   cout << "Copy_constructor called." << endl;
	}
	~Point()
	{
		cout << X << "," << Y << " Object destroyed." << endl;
	}
	int  GetX() { return X; }		int GetY() { return Y; }
private:   int  X, Y;
};

void f(Point  p)
{
	cout << "Funtion:" << p.GetX() << "," << p.GetY() << endl;
}

void main()
{
	Point A(1, 2);
	f(A);
	system("pause");
}

运行结果:

五、第四种用法:函数返回类类型时,通过复制构造函数建立临时对象

#include "iostream"
using namespace std;


class Point
{
public:
	Point(int xx = 0, int yy = 0)
	{
		X = xx;  Y = yy;  cout << "Constructor Object.\n";
	}
	Point(const Point & p) 	    //复制构造函数
	{
		X = p.X;  Y = p.Y;   cout << "Copy_constructor called." << endl;
	}
	~Point()
	{
		cout << X << "," << Y << " Object destroyed." << endl;
	}
	int  GetX() { return X; }		int GetY() { return Y; }
private:   int  X, Y;
};

Point g()
{
	Point A(1, 2);
	return A;//把局部对象A复制到匿名对象
}

void main()
{
	Point B;
	B = g();
	system("pause");
}

运行结果:


 


 


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值