【问题标题】:Use assignment operators instead of an implicit constructor使用赋值运算符而不是隐式构造函数
【发布时间】: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


【解决方案1】:

MyClass my_class = 2.; 或多或少等同于 MyClass my_class(2.);,但是,您将构造函数标记为 explicit,这会阻止 C++ 自动执行此操作。

因此,以您编写代码的方式,您无法真正做您想做的事。您可以使用以下方式显式调用构造函数:

MyClass my_class(2.); // Explcitly call your constructor

或者,正如 Ted Lyngmo 在 cmets 中提到的,您可以这样做:

MyClass my_class; // Call your constructor with default argument of 0
my_class = 2.; // then call your assignment operator

【讨论】:

    猜你喜欢
    • 2020-09-06
    • 2011-02-16
    • 2015-10-14
    • 2017-01-21
    • 2011-02-20
    • 2011-12-12
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多