由函数返回初始化的构造函数
Constructor initialized by function return
我无法理解为什么我不能在一行中初始化我的类对象,如下所示。 收到对我来说并不简单的VS错误:
">错误:E0334 类"示例"没有合适的复制构造函数"
和
"C2440'正在初始化':无法从'示例'转换为'示例'">
一些代码:
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));
通过没有错误,可以吗?
复制构造函数中缺少const
example(example const &);
为什么要像这样初始化 object2:
example object2(object1.sum(a,b));
获取错误
因为您无法从右值object1.sum(a,b)
获取非常量引用。
但像这样:
example object2; object2(object1.sum(a,b));
可以吗?
这段代码也是错误的,第二行需要operator ()
。
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));
没关系,因为,它会调用编译器自动生成的复制赋值运算符(当你像我一样添加移动构造函数时,编译器不会生成复制赋值运算符(
相关文章:
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 如何在 C++ 中使用它的构造函数初始化 unique_ptrs 的 2D 向量?
- 在C++中使用默认构造函数初始化对象的不同方法
- 使用默认构造函数初始化对象的不同方法
- 我们可以用参数化构造函数初始化结构的数组吗?
- 有没有办法使用该类的构造函数初始化另一个类的私有部分内的对象数组?
- 类内初始化与构造函数初始化列表的顺序
- 通过 C++ 中的重载构造函数初始化未知类型的变量
- 使用复制构造函数初始化 new[]
- 如何从子类的构造函数初始化父类的私有成员
- 在构造函数初始化列表中使用 std::variant
- 使用构造函数初始化结构还是在之后设置其值更好?
- C++ 没有匹配的构造函数初始化 []
- 我正在使用dev c ++,但收到错误(C++98'array'必须由构造函数初始化)
- 使用所述填充构造函数初始化向量中的向量
- 如何同时创建一个具有两个或多个构造函数初始化的对象
- 在 new 关键字中,由默认构造函数初始化的类中的元素是否也使用 new 关键字在C++?
- 这是使用构造函数初始化数组对象的最佳方法吗?
- 内置类型的构造函数初始化
- 构造函数初始化和对象损坏