zoukankan      html  css  js  c++  java
  • 使用new分配内存的类需要自己定义拷贝构造函数

    13.22 假定我们希望HasPtr的行为像一个值。即,对于对象所指向的string成员,每个对象都有一份自己的拷贝。

    #include<iostream>
    #include<string>
    #include<new>
    
    using namespace std;
    class HasPtr
    {
    public:
        HasPtr(const string &s=string()):ps(new string(s)),i(0){cout<<"constructer"<<endl;}
        HasPtr(const HasPtr &h):i(h.i)
        {
            cout<<"copy constructer"<<endl;
            ps=new string;
            *ps=*h.ps;//只拷贝值
        }
        HasPtr& operator=(const HasPtr &h)
        {
            auto newp=new string(*h.ps);
            delete ps;
            ps=newp;
            i=h.i;
            return *this;
        }
        ~HasPtr() {  delete ps; cout<<"destructer"<<endl;}
    private:
        string *ps;
        int i;
    };
    int main()
    {
        HasPtr h;
        HasPtr hh(h);
        hh=h;
        return 0;
    }
  • 相关阅读:
    0806 c#总复习
    0804 递归
    0808 html基础
    0803结构体,枚举类型
    0801out传值
    0731函数
    0730特殊集合
    0728多维数组,ArrayList集合
    js 获取url链接的任意参数
    jq dom操作
  • 原文地址:https://www.cnblogs.com/wuchanming/p/3925520.html
Copyright © 2011-2022 走看看