首页 > 解决方案 > 由函数返回初始化的构造函数

问题描述

我不明白为什么我不能像下面这样在一行中初始化我的类对象。得到对我来说并不简单的 VS 错误:

“错误:E0334 类“示例”没有合适的复制构造函数”

“C2440 '初始化':无法从 'example' 转换为 '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));

通过没有错误,可以吗?

标签: c++constructorreturn-value

解决方案


const复制构造函数中缺少 a

example(example const &);

为什么要像这样初始化 object2:

example object2(object1.sum(a,b));

出错

因为您无法从 rvalue 获得非常量引用object1.sum(a,b)

但像这样:

example object2;
object2(object1.sum(a,b));

好吗?

这段代码也是错误的,第二行需要一个operator ().


推荐阅读