首页 > 解决方案 > 在 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 也是正确的。

关于表达式中的顺序的任何见解?

标签: c++

解决方案


推荐阅读