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

来源:互联网 发布:荣耀盒子 软件安装 编辑:程序博客网 时间:2024/06/05 16:51

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;}




0 0