C++ - 奇怪的代码输出

C++ - Weird code output

本文关键字:代码 输出 C++      更新时间:2023-10-16

这段代码:

class A {
public:
    int _a;
    A():_a(0) { cout << "A default - ctor, ";}
    A(int i):_a(i) { cout << "A int - ctor, ";}
    operator int() { cout << "A int - operator, "; return 33;}
    virtual ~A() { cout << "A dtor, ";}
};
int main() {
    A* a = new A(99);
    cout << *a << endl;
    return 0;
}

我预计输出是:A int-operator, A int-ctor, 33

但真正的输出是:A int-ctor, A int-operator, 33

首先你调用 "new A(99)" ,它调用 "A(int i)" ,它打印"A int - ctor, "

下面的行调用 "cout << *a" ,它调用 "operator int()" ,它打印"A int - operator, "

然后该行以 "cout << [result] << endl" 完成,这将打印结果 (33) 和一个换行符。

所以"A int - ctor, " + "A int - operator, " + "33" + "endl""A int - ctor, A int - operator, 33".