记一次C++拷贝构造函数带来问题

C++拷贝构造函数是类对象初始化赋值,拷贝传参等情况时使用的重要函数。

一般情况下,普通的类型进行初始化赋值是十分容易的,例如:

int a = 0;
但是如果是对一个类对象呢?

目前我们有如下一个类,正常使用没问题:

#include <iostream>
using namespace std;

class Test{
public:
	int a;
	Test(){
		a = 0;
	}
};

int main(int argc, char **argv)
{
	Test t;
	cout << t.a << endl;
	return 0;
}

但如果需要

Test a = t;

这时,就需要调用其拷贝构造函数:

#include <iostream>
using namespace std;

class Test{
public:
	int a;
	Test(){
		a = 0;
	}
	Test(Test& p){ //这里就是拷贝构造函数的用法,将一个类的引用传入即可。
		this->a = p.a;
	}
};

int main(int argc, char **argv)
{
	Test t;
	cout << t.a << endl;
	Test a = t;
	cout << a.a <<endl;
	return 0;
}


看起来是没什么问题的,但是,如果是下面这种情况呢?

#include <iostream>
#include <map>
using namespace std;


class Test{
public:
	int a;
	Test(){
		a = 0;
	}
	Test(Test& p){
		this->a = p.a;
	}
};

map<int,Test> test_map;

int main(int argc, char **argv)
{
	Test p;
	test_map[0] = p;
	cout << test_map[0].a << endl;
	return 0;
}

我们使用了map模板类,并使用重载的赋值操作符给我们的map对象赋值。

这时编译不能在g++下通过:

/usr/include/c++/4.8/bits/stl_pair.h:119:39: error: no matching function for call to ‘Test::Test(const Test&)’
  : first(__p.first), second(__p.second) { }

这段错误是在说,我们的stl_pair要求的构造函数是一个带有const约束的参数,将拷贝构造函数修正后编译成功:

Test(const Test& p){
	this->a = p.a;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值