1. 程式人生 > >c++中賦值運算符中的隱式轉換

c++中賦值運算符中的隱式轉換

字符串 {} new () 再看 null del delete ret

先上代碼:

#include<iostream>
#include<string>
using namespace std;

class MyStr
{
private:
    char *name;
    int id;
public:
    MyStr() {}
    MyStr(int a) {
        cout<< a<<endl;
    }
    MyStr(int _id, char *_name)   //constructor
    {
        cout << "constructor" << endl;
        id = _id;
        name = new char[strlen(_name) + 1];
        strcpy(name, _name);
    }
    MyStr(const MyStr& str)
    {
        cout << "copy constructor" << endl;
        id = str.id;
        if (name != NULL)
            delete name;
        name = new char[strlen(str.name) + 1];
        strcpy(name,  str.name);
    }
    MyStr& operator =(const MyStr& str)//賦值運算符
    {
        cout << "operator =" << endl;
        if (this != &str)
        {
            if (name != NULL)
                delete name;
            this->id = str.id;
            int len = strlen(str.name);
            name = new char[len + 1];
            strcpy(name,  str.name);
        }
        return *this;
    }
    ~MyStr()
    {
        delete name;
    }
};

int main()
{
//    MyStr str1(1, "hhxx");
//    cout << "====================" << endl;
    MyStr str2;
//    str2 = str1;
    str2 = 19;
    cout << "====================" << endl;
    MyStr str3 = str2;
    return 0;
}

str2 = 19; 這一句第一步先看有沒有重載=號運算。
有 。第二步。再看你有沒有把字符串類類轉換成重載=號運算的參數類型。這裏是const MyStr&(用const 的原因是為了讓大範圍的類型可以轉換成小範圍的) 。就是找有沒有 int 型的構造函數。
第三步。有先調用 int 型構造函數。再調用賦值運算符。
也就是 c++很智能會自動隱式轉換。前提是有對應類型的構造函數。

c++中賦值運算符中的隱式轉換