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