记一次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
- 记一次C++拷贝构造函数带来问题
- 【C++】拷贝构造函数
- C++:拷贝构造函数
- c++"拷贝构造函数
- C++: 拷贝构造函数
- 【C++】拷贝构造函数
- c++::拷贝构造函数
- 【C++】:拷贝构造函数
- 【C++】拷贝构造函数
- C++:拷贝构造函数
- 一次函数默认值带来的问题
- C++_拷贝构造函数
- C++_拷贝构造函数
- 拷贝构造函数(C++)
- 拷贝构造函数(C++)
- C/C++ 拷贝构造函数
- c++(拷贝构造函数)
- 使用缺省的拷贝构造函数带来的危险性
- <高质量C>C语言基础和变量(二)
- 阅读KJFrameAndroid--各种基类和控件注入
- 浴柜行业抓住机遇 电商之路很辉煌
- 建造者模式(Builder)
- 第十一周项目六:回文素数
- 记一次C++拷贝构造函数带来问题
- Android SDK更新 Connection to http://dl-ssl.google.com refused 解决方法
- flashback table快速恢复误删除的数据
- 大数据实时计算工程师/Storm工程师职业学习路线图
- uva10192-Vacation
- rpath添加依赖库搜索路径
- SQL Server 致程序员(容易忽略的错误)
- JQuery/Javascript两个控件的focus和blur事件
- 【Leetcode】4Sum (Sum)