#include <iostream>
#include <cstring>
using namespace std;
class MyString : public string {
public:
MyString(const char* s) :string(s) {}
MyString(const string& str) : string(str) { cout << "why is this line invoked?"; }
};
int main() {
MyString s1("s1-"), s2("s2-");
s2 = s1+s2; //I thought this line would be an assignment operation for s2. Not sure why constructor from line 7 is invoked?
return 0;
}
我试图从string class
继承MyString
类。我想知道为什么s2=s1+s2
会从MyString
调用构造函数.这不是赋值操作,而不是初始化吗?谢谢!!
由于MyString
类没有重载的二进制operator+
,因此编译器必须对operator+
使用std::string
重载。
其结果是另一个std::string
,然后用于构造要分配给s2
的MyString
对象。