明天早上我正在爲自己的考試做準備。我正在努力處理下面的C++演練。 我已經運行代碼並使用cout來檢查程序的執行情況。我注意到第一件事,那就是程序在類「one」中爲默認的構造函數調用了3次,只是爲main中的第一個對象調用。我對代碼的執行感到困惑。如何知道在C++中有2個類時使用哪個類?
#include <iostream>
using namespace std;
class one {
int n;
int m;
public:
one() { n = 5; m = 6; cout << "one one made\n"; }
one(int a, int b) {
n = a;
m = b;
cout << "made one one\n";
}
friend ostream &operator<<(ostream &, one);
};
ostream &operator<<(ostream &os, one a) {
return os << a.n << '/' << a.m << '=' <<
(a.n/a.m) << '\n';
}
class two {
one x;
one y;
public:
two() { cout << "one two made\n"; }
two(int a, int b, int c, int d) {
x = one(a, b);
y = one(c, d);
cout << "made one two\n";
}
friend ostream &operator<<(ostream &, two);
};
ostream &operator<<(ostream &os, two a) {
return os << a.x << a.y;
}
int main() {
two t1, t2(4, 2, 8, 3);
cout << t1 << t2;
one t3(5, 10), t4;
cout << t3 << t4;
return 0;
}
我不明白第一件事。當主要調用第一個默認構造函數two t1,
爲什麼它被連續調用三次然後它會調用t2(4, 2, 8, 3);
?
如果代碼太長,我很抱歉,但我真的需要幫助才能理解它。
請指教。謝謝。
請詳細說明你的問題,你不能從這個代碼明白什麼? – SMK 2012-04-10 05:01:33
C++允許特定的優化,在某些情況下,編譯器可能會刪除臨時對象。這使得更難預測將調用多少構造函數。編譯器在調試時會留下額外的ctor調用是很常見的,但在最終版本中刪除它們。 – MSalters 2012-04-10 07:28:44