我有以下代碼[這是一個面試問題]:C++默認情況下,複製和推廣的構造
#include <iostream>
#include <vector>
using namespace std;
class A{
public:
A(){
cout << endl << "base default";
}
A(const A& a){
cout << endl << "base copy ctor";
}
A(int) {
cout << endl << "base promotion ctor";
}
};
class B : public A{
public:
B(){
cout << endl << "derived default";
}
B(const B& b){
cout << endl << "derived copy ctor";
}
B(int) {
cout << endl << "derived promotion ctor";
}
};
int main(){
vector<A> cont;
cont.push_back(A(1));
cont.push_back(B(1));
cont.push_back(A(2));
return 0;
}
輸出是:
base promotion ctor
base copy ctor
base default
derived promotion ctor
base copy ctor
base copy ctor
base promotion ctor
base copy ctor
base copy ctor
base copy ctor
我無法理解這種輸出,特別是爲什麼基本默認被調用一次,最後3個拷貝ctor。有人可以解釋這個輸出嗎?
謝謝。
請回複評論或提出新問題。這是一個新問題,不是嗎? –
是的,編輯是一個單獨的問題;我曾嘗試保留()。 – Jake
他們的確切順序 - http://ideone.com/TUEGo –