c++ - 由函数返回初始化的构造函数
问题描述
我不明白为什么我不能像下面这样在一行中初始化我的类对象。得到对我来说并不简单的 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));
通过没有错误,可以吗?
解决方案
您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 ()
.
推荐阅读
- javascript - 如何解决 HTTP/1.1 POST 405 Method Not allowed 错误
- javascript - 缩进问题
- r - 涉及 numeric(0) 值的加法
- php - PHP 自动加载类/子类
- domain-driven-design - DDD Relate Aggregates 在一个长时间运行的进程中
- java - 使用 Primefaces 在 Java Spring Boot 中循环列表数据
- java - 如何修复错误“未处理的异常类型异常”
- r - 创建新变量,其中不在第 1 个和第 99 个百分位数之间的所有值都替换为缺失值 (NA)
- python - 熊猫试图在列上分组后将列中的值变成新列
- ios - UITableView 将单元格拖放到最后一个单元格下方的列表底部