C++拷贝、赋值与销毁
2016-11-08 02:48
295 查看
copy
当用一个类的变量去初始化一个类的时候,会复制出该类的一个副本,而不是淡出的引用,即,改变新的变量,原来的变量不会改变。用构造函数或者赋值均会复制出该类的一个副本。
代码
#include<iostream> #include<exception> #include<fstream> #include<sstream> #include<string> #include<vector> #include<iterator> #include<list> #include<deque> #include<stack> #include<queue> #include<concurrent_priority_queue.h> #include<algorithm> #include<numeric> #include<functional> //bind #include<map> #include<set> #include<unordered_map> #include<memory> using namespace std; class TestCopy { public: int num[10]; string str; TestCopy(int n, string s) { num[0] = n; str = s; } }; int main() { cout << "start!" << endl; TestCopy tc1(1, "233"); TestCopy tc2(tc1); tc2.num[0] = 3; tc2.str = "after-change"; cout << "test copy 1 : " << tc1.num[0] << ", " << tc1.str << endl; cout << "test copy 2 : " << tc2.num[0] << ", " << tc2.str << endl; TestCopy tc3 = tc1; tc3.num[0] = 100; cout << "test copy 1 : " << tc1.num[0] << ", " << tc1.str << endl; cout << "test copy 3 : " << tc3.num[0] << ", " << tc3.str << endl; cout << "end!" << endl; system("pause"); return EXIT_SUCCESS; }
上面的代码中,
tc1复制后生成了
tc2,修改
tc2,
tc1不发生改变。修改
tc3,
tc1也不发生改变。
左值和右值
返回值是引用类型,且没有被const修饰时,可以将其返回值作为左值
代码
#include<iostream> #include<exception> #include<fstream> #include<sstream> #include<string> #include<vector> #include<iterator> #include<list> #include<deque> #include<stack> #include<queue> #include<concurrent_priority_queue.h> #include<algorithm> #include<numeric> #include<functional> //bind #include<map> #include<set> #include<unordered_map> #include<memory> #include<assert.h> using namespace std; char &lV(string &a, int idx) { assert((!a.empty()) && a.length() > idx); return a[idx]; } int main() { cout << "start!" << endl; string s("ABCDEF"); cout << s << endl; lV(s, 0) = 'Z'; cout << s << endl; cout << "end!" << endl; system("pause"); return EXIT_SUCCESS; }
参考链接:http://blog.csdn.net/sunshinewave/article/details/7830701
相关文章推荐
- C++ 中类的拷贝、赋值、销毁的实例详解
- C++中的拷贝、赋值和销毁
- C++对象的拷贝与赋值操作
- 复习几个C++概念:声明与定义、传值与拷贝构造、初始化和赋值
- C++ Primer : 第十三章 : 拷贝控制之拷贝、赋值与销毁
- C++ 类的三种构造函数(默认构造,拷贝构造,赋值构造),在什么情况下会被调用
- c++构造函数 && 拷贝,赋值,析构
- C++ 赋值运算和拷贝赋值函数的区别
- C++二叉树之构造拷贝赋值,递归和非递归的前序遍历,中序遍历和后序遍历,以及层序遍历
- GeekBand学习笔记:C++三大函数:拷贝构造、拷贝赋值、析构函数
- c++ primer 学习笔记12--拷贝赋值,销毁
- C++中的拷贝构造,赋值和移动构造
- C++对象的拷贝与赋值操作
- C++ 对象构造, 拷贝, 赋值和隐式类型转换总结
- C++学习笔记-类5-浅拷贝和深拷贝以及赋值操作符的重载
- 请用c++ 实现stl中的string类,实现构造,拷贝构造,析构,赋值,比较,字符串相加,获取长度及子串等功能
- C++对象的拷贝与赋值操作
- 关于C++中的赋值与拷贝
- 拷贝控制之拷贝、赋值、销毁
- python 赋值 浅拷贝 深拷贝 与c++ 比较