C++拷贝、赋值与销毁

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,修改tc2tc1不发生改变。修改tc3tc1也不发生改变。

左值和右值

  • 返回值是引用类型,且没有被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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

littletomatodonkey

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值