在声明上为类赋值不会编译
assigning class a value on declaration does not compile
我想在声明时为类赋值,所以我做了这个基本类:
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
相关文章:
- 为"adjacent"变量赋值时出现问题
- C++中的赋值发生,尽管右侧出现异常
- 程序无法编译:将 'int (*)[3][3]' 赋值为 'int [9][3][3]' 中的不兼容类型
- 为什么在直接初始化和赋值中传递 lambda 而不是在复制初始化中传递 lambda 时会编译?
- 如何重载 const 对象的 [],以便值赋值不会导致编译错误
- 在声明上为类赋值不会编译
- 常量引用向量向量<向量<long>>赋值不编译
- 在编译时为变量赋值
- 重载运算符 = 不使用赋值进行编译
- 我无法让这段代码为赋值编译(请参阅代码后的注释)
- 值的赋值运算符未使用显式复制构造函数进行编译
- 赋值给右值:为什么要编译
- 编译-vs运行时常量变量赋值和C++中vlas的分配
- 如果尝试将负数赋值给无符号容器,是否会导致编译错误?
- 定义赋值运算符 = 只允许零 RHS,否则无法编译
- 是否有可能在编译时检测到以下赋值
- 为什么对基类的赋值有效,但对派生类的赋值是编译错误
- c++删除了移动赋值运算符的编译问题
- 当使用-O2编译时,程序跳过赋值
- 为什么C++允许在具有指针成员的类中编译默认的复制构造函数/赋值运算符重载