【发布时间】:2021-07-27 06:08:37
【问题描述】:
在我的程序中,我正在尝试使用赋值 operator= 来分配我班级的一个对象。我特别尝试调用赋值运算符而不是隐式构造函数(因此是 explicit 关键字)。当我尝试编译时,我得到一个C2440 Compiler Error:
class MyClass {
public:
explicit MyClass(double x = 0.) :
m_x(x) {
}
MyClass& operator = (const double& other) {
m_x = other;
/* do something special here */
return *this;
}
private:
double m_x;
};
int main()
{
MyClass my_class = 2.; // C2440
return 0;
}
我猜编译器尝试隐式调用构造函数失败(因为explicit)。有人解决了吗?
【问题讨论】:
-
MyClass my_class; my_class = 2.;是一个可接受的解决方案吗? -
Does anyone have a fix?删除explicit?有什么需要解决的 - 一切都按预期工作 - 编译器失败了应该失败的代码。你想怎么解决? -
MyClass my_class = 2.;或多或少等同于MyClass my_class(2.);,但是,您在explicit中说过,这使得它无效。 -
@ChrisMM 这是明确的,所以......作为答案 - 即使它不使用赋值运算符
-
MyClass my_class = 2;中没有运算符,因此隐藏构造函数永远不会神奇地调用赋值运算符。根据 C++ 语法,这是一个带有复制初始化的变量定义。它不会因为您的构造函数被显式声明而成为其他语法生成(尽管 C++ 具有状态语法,所以 可以 以不同的方式解析,这个例子没有)
标签: c++ constructor implicit assignment-operator explicit