在声明上为类赋值不会编译

assigning class a value on declaration does not compile

本文关键字:编译 赋值 声明      更新时间:2023-10-16

我想在声明时为类赋值,所以我做了这个基本类:

class   A
{
public:
    A   &operator=(int)
    {
        return (*this);
    }
};

并用这个主要编译它:

int main(void)
{
    A x = 1;
}

但是编译器抱怨了以下错误消息:

no viable conversion from 'int' to 'A'
    A x = 1;
      ^   ~

但是当我用这个主要编译时:

int main(void)
{
    A x;
    x = 1;
}

一切都编译顺利


为什么我的第一个 main 不编译,我如何更改类 A 以便它编译?

A x = 1;是初始化,而不是赋值;它们是不同的东西。它不调用赋值运算符,但需要转换构造函数。

class   A
{
public:
    // converting constructor
    A (int) {} 
    A   &operator=(int)
    {
        return (*this);
    }
};

然后

A x = 1; // initialize x via converting constructor
x = 2;   // assign x via assignment operator