先上代码:
- #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++ 很智能会自动隐式转换前提是有对应类型的构造函数
来源: http://www.bubuko.com/infodetail-2493748.html