三大函数

2017-12-15  本文已影响0人  qyfl

三大函数

class string{
private:
    char* data;

public:
    ...

    // 构造函数
    string(const char* value = nullptr) {
        if(value) {
            data = new char[strlen(value) + 1];
            strcpy(data, value);
        }
        else {
            data = new char[1];
            *data = "\0";
        }
    }

    // 拷贝构造
    string(const string& value) {
        data = new char[strlen(value) + 1];
        strcpy(data, value);
    }

    // 拷贝赋值
    string& operator = (const string& value) {
        //自我赋值检测
        if(this == &vlaue)
            return *this;

        //注意实现细节
        delete[] data;
        data = new char[strlen(value) + 1];
        strcpy(data, value);
    }

    // 析构函数
    ~string() {
        delete[] data;
    }
};

拷贝构造

string s("hello");
string s1(s);

拷贝赋值

string s("hello");
string s1("world");

s1 = s;

析构函数

{
    string s("hello,world");
}
// s 的析构函数调用
上一篇 下一篇

猜你喜欢

热点阅读