我在将 int 分配给对象时遇到问题,如下所示:
int main() {
Wurzel a;
Wurzel b=3; // error: conversion from 'int' to non-scalar type 'Wurzel' requested
return 0;
}
我的带有赋值运算符的类:
class Wurzel{
private:
int wurzelexponent;
int wert;
public:
Wurzel(){
wurzelexponent=1;
wert=1;
}
Wurzel& operator =(const Wurzel &w) {
wurzelexponent = w.wurzelexponent;
}
};
我必须使用 =
运算符来执行此操作
问题出在哪里?
最佳答案
I must do this with = operator
不,你不能。因为 Wurzel b=3;
不是赋值,而是初始化,copy initialization 。正如错误消息所述,您需要 converting constructor来完成它。
class Wurzel{
...
public:
...
Wurzel(int x) : wurzelexponent(x), wert(1) {}
Wurzel(int x, int y) : wurzelexponent(x), wert(y) {}
...
};
然后
Wurzel b = 3; // Wurzel::Wurzel(int) will be called
Wurzel b = {3, 2}; // Wurzel::Wurzel(int, int) will be called [1]
注意,operator=
仅用于赋值,如:
Wurzel b; // default initialized
b = something; // this is assignment, operator=() will be used
[1]从C++11引入了具有多个参数的转换构造函数。
关于c++ - 从 'int' 到非标量类型赋值运算符的转换 - object 到 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38543308/