我不明白为什么我不能像下面这样在一行中初始化我的类对象。获取对我来说并不简单的VS错误:
错误:E0334类"example“没有合适的复制构造函数
和
“示例‘初始化’:无法从‘C2440’转换为'example'”
下面是一些代码:
class example {
public:
example() { R = 0.F; I = 0.F; };
example(float, float);
example(example &);
example sum( float, float);
private:
float R, I;
};
example::example(float s1, float s2):R(s1), I(s2) {}
example::example(example & ex2) {
R = ex2.R;
I = ex2.I;
}
example example::sum(float s1, float s2){
example s;
s.R = s1;
s.I = s2;
return s;
}
int main() {
float a = 2;
float b = 4;
example object1(1,1);
example object2(object1.sum(a,b));
return 0;
}
为什么要这样初始化object2
:
example object2(object1.sum(a,b));
获取错误,但如下所示:
example object2;
object2 = (object1.sum(a,b));
没有错误地通过,可以吗?
发布于 2018-06-04 09:08:48
example object2(object1.sum(a,b));
这不是复制构造函数,这是移动构造函数,因为参数是右值。
因此,您可以像这样显式地添加移动构造函数。
class example {
public:
example() { R = 0.F; I = 0.F; };
example(float, float);
example(example &);
//move
example(example &&);
example sum( float, float);
private:
float R, I;
};
example::example(float s1, float s2):R(s1), I(s2) {}
example::example(example & ex2) {
R = ex2.R;
I = ex2.I;
}
example::example(example && ex2){
R = ex2.R;
I = ex2.I;
}
example example::sum(float s1, float s2){
example s;
s.R = s1;
s.I = s2;
return s;
}
int main() {
float a = 2;
float b = 4;
example object1(1,1);
example object2(object1.sum(a,b));
return 0;
}
还有这个
example object2;
object2 = (object1.sum(a,b));
是可以的,因为它将调用编译器自动生成的复制赋值运算符(当您像我一样添加移动构造函数时,编译器不会生成复制赋值运算符)
https://stackoverflow.com/questions/50672301
复制相似问题