c++ - 在 C++ 中,构造函数和运算符的顺序是什么?
问题描述
这是ECE220期末考试的一道题
#include <stdio.h>
class THING {
int x;
public:
THING() :x(1) {
printf("ONE ");
}
THING(int val) : x(val) {
printf("%d ", val);
}
THING& operator=(const THING &t) {
this->x = t.x + 10;
printf("= %d", this->x);
return *this;
}
friend THING operator+(const THING &t, const THING &u) {
printf("-> ");
return THING(t.x * u.x);
}
};
THING* function() {
printf("line 1: ");
THING t(1); // t.x is 1
printf("\nline 2: ");
THING u = (t + 3) + 5; // u.x is 15 // in here operator t will not be used, instead it will call a construction function //copy construction
}
int main(int argc, char const *argv[]) {
function();
return 0;
}
输出
第 1 行:1
第 2 行:5 3 -> 3 -> 15
第 3 行:16 -> 240
line2 输出可以是 3 -> 3 5 -> 15,这也是这个问题的解决方案。
我不明白为什么 5 3 -> 3 -> 15 也是正确的。
关于表达式中的顺序的任何见解?
解决方案
推荐阅读
- javascript - JSON数组在读取时被拆分为字母
- junit - CircleCI:如何配置测试结果存储?
- compilation - 使用 LLVM 的成语识别
- vue.js - 当按下除输入按钮 vue.js 之外的所有其他键时,将布尔值设置为 false
- php - 未插入表中的值
- asp.net-mvc-5 - 通过 azure AD 进行身份验证时公开扩展属性 - Azure AD 中的声明感知应用程序
- html - 方形空间中的图像砌体网格
- excel - Excel VBA帮助_允许用户删除
- java - Kafka Streams:KTable 到 KStream 一对多的转换
- multilabel-classification - 使用 mlr 包的多标签分类错误