簡體   English   中英

C++ - 奇怪的代碼輸出

[英]C++ - Weird code output

此代碼:

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;
}

我希望輸出是:一個 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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM