转换 - 对象为int
我有分配INT问题反对这样的:转换 - 对象为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;
}
};
我必须这样做=
运营商
问题在哪里?
我必须用=操作
没有做到这一点,你不能。因为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。
您试图assing一个int:Wurzel b=3;
,但你的运营商=只重载const Wurzel &w
。它的参数是Wurzel
,不是int,int不能隐式转换为Wurzel
。要修复,可以添加另一个运算符:
Wurzel& operator =(int i)
{}
问题是所需功能未定义。
一个解决方案是超载=
运营商接受int
。
试试这个:
class Wurzel{
private:
int wurzelexponent;
int wert;
public:
Wurzel(){
wurzelexponent=1;
wert=1;
}
// this is constructor, not = operator
/*
Wurzel(int a) {
wurzelexponent = a;
wert = a;
}
*/
Wurzel& operator =(const Wurzel &w) {
wurzelexponent = w.wurzelexponent;
return *this; // you should return something
}
Wurzel& operator=(int a) {
// implement as you like
wurzelexponent = a;
return *this;
}
};
int main() {
Wurzel a;
// this is not = operator but initializing
//Wurzel b=3;
Wurzel b;
b = 3; // this is = opetator, which you say you must use
return 0;
}
好的,但为什么我不能使用'Wurzel b = 3'?我不能直接分配?为了您的解决方案,我的操作员需要'Wurzel&operator =(const Wurzel&w)' – lukassz
您可以*直接初始化*(通过调用构造函数),但不能直接执行*赋值*(使用赋值运算符)。 'Wurzel b = 3;'可以通过定义正确的构造函数来完成,但是你必须使用'='运算符,所以你必须在某处使用它 - 也许在构造函数的定义中?这个程序中不需要您的操作员。 – MikeCAT
构造函数的定义?你究竟是什么意思?问题是,在课堂上,我有两个变量,然后我必须以某种方式区分他们,如果我分别启动他们。 – lukassz
不,不是'运营商='但一个构造函数将被调用'吴志祥B = 3;'。 – MikeCAT