此代码:
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,一个int-ctor,33
但真正的输出是: 一个int-ctor,一个int-operator,33
答案 0 :(得分:3)
首先拨打"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"
。