【发布时间】:2021-12-29 12:34:59
【问题描述】:
我对以下代码有疑问。在主函数中会发生什么时行:obj = 20;被执行。我不明白为什么它调用构造函数?谁能解释一下?
#include <iostream>
#include <string>
using namespace std;
class Int {
int x;
public:
Int(int x_in = 0)
: x{ x_in }
{
cout << "Conversion Ctor called" << endl;
}
operator string()
{
cout << "Conversion Operator" << endl;
return to_string(x);
}
};
int main()
{
Int obj(3);
string str = obj;
obj = 20;
string str2 = static_cast<string>(obj);
obj = static_cast<Int>(30);
return 0;
}
【问题讨论】:
-
编译器会列出
Int.operator=(int)的可能候选对象,其中之一是Int.operator=(Int const& value = Int(20))。这些候选人基于排名,而那个特定的候选人获胜。您可以通过explicit标记它来删除构造函数:explicit Int(int x_in = 0) -
@Eljay 实际上是
Int.operator=(Int&& value = Int(20))获胜。
标签: c++ constructor type-conversion typecasting-operator