C++ 类的赋值和拷贝


#include "stdafx.h"
#include <string.h> 
#include <iostream>

 class A
{
public:
	A() {}
	~A() {
		std::cout << "析构" << std::endl;
	}

	A(int id, char* username_) :_id(id),username(username_) {}

	A(A &a);//重载拷贝函数
	A& operator=(A &b);//重载赋值函数,形参为引用,避免了一次对象的拷贝构造
					   //或者 我们也可以这样重载赋值运算符 void operator=(A &a);即不返回任何值。如果这样的话,他将不支持客户代买中的链式赋值 ,例如a=b=c will be prohibited!

	int GetId() { return _id; }
	char* GetName() { return username; }

	void SetId(int id) { _id = id; }
	void SetUsername(char* name) { 
		username = new char[strlen(name) + 1];
		if (username != NULL)
			strcpy(username, name);
	}
private:
	int _id;
	char *username;
};

A::A(A &a)
{
	std::cout << "调用拷贝构造函数" << std::endl;
	_id = a._id;
	username = new char[strlen(a.username) + 1];
	if (username != NULL)
		strcpy(username, a.username);
}

A& A::operator = (A &a)
{
	std::cout << "调用重载" << std::endl;
	if (this == &a)//  问:什么需要判断这个条件?(不是必须,只是优化而已)。答案:提示:考虑a=a这样的操作。
		return *this;
	if (username != NULL)
		delete username;
	_id = a._id;
	username = new char[strlen(a.username) + 1];
	if (username != NULL)
		strcpy(username, a.username);
	return *this;
}
//另外一种写法:
//void A::operator = (A &a)
//{
//	if (username != NULL)
//		delete username;
//	_id = a._id;
//	username = new char[strlen(a.username) + 1];
//	if (username != NULL)
//		strcpy(username, a.username);
//}


void  testFun(A* pA) //指针是一个变量,作为参数,会有值拷贝,所以最好用引用
{
}



int main()
{

	char name[] = "user1";
	A a1(11,name);

	A a2;
	// 如果对象在申明之后,在进行的赋值运算,我们称之为赋值运算
	a2 = a1;
	std::cout << a2.GetId() << std::endl;
	std::cout << a2.GetName() << std::endl;

	//  如果对象在声明的同时马上进行的初始化操作,则称之为拷贝运算
	//在建立一个新对象时,使用一个已经存在的对象去初始化这个新对象,系统就会自动调用拷贝构造函数
	A a33(a2);
	A a3=a2;


	std::cout << "-----------------" <<std::endl;
	//
	A* a4=new A(4, name);
	A* a5 = new A();
	a5->SetId( a4->GetId());
	a5->SetUsername(a4->GetName());
	std::cout<< a5->GetId()<<std::endl;
	delete a4;
	delete a5;

	std::cout << "-------" << std::endl;
	system("pause");
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值