为什么在赋值操作中调用构造函数?


#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,然后用于构造要分配给s2MyString对象。

最新更新