#include <iostream>using namespace std;class Base{private:int data;public:Base(int _data = 1){cout<<"Base(int _data = 1)"<<endl;//cout<<"this->"<<this<<endl;data = _data;//this->display();}Base(const Base& another){cout<<"Base(const Node& another)"<<endl;data = another.data;}Base& operator=(const Base& another){cout<<"operator = "<<endl;data = another.data;return *this;}void display(){cout<<"display()"<<endl;}};class Drive{private:Base base;public:Drive(const Base& another){cout<<"Drive(const Base& another)"<<endl;//cout<<"another->"<<&another<<endl;//cout<<"Drive this->"<<this<<endl;base = another;}};int main(){cout << "Hello world!" << endl;Base tmp(55);cout<<"-------------"<<endl;//cout<<"tmp ->"<<&tmp<<endl;Drive test(tmp);return 0;}上面代碼的輸出會多出來一個Base(int _data)的調(diào)用,所以我想知道的是Drive(const Base& another)函數(shù)的具體執(zhí)行過程???求幫忙解答
1 回答

ibeautiful
TA貢獻1993條經(jīng)驗 獲得超6個贊
lass Drive
{
private:
Base base;
public:
Drive(const Base& another)
{
//構(gòu)造前先默認構(gòu)造成員變量base,調(diào)用Base(int _data = 1)
cout<<"Drive(const Base& another)"<<endl;
base = another; //此處調(diào)用的是Base& operator=(const Base& another)
}
};
另一種方式,也是高級程序員該用的方式,效率高些:
class Drive
{
private:
Base base;
public:
Drive(const Base& another):base(another) //此處為成員初始化列表,在此處通過拷貝構(gòu)造直接初始化base,調(diào)用Base(const Base& another)
{
cout<<"Drive(const Base& another)"<<endl;
}
};
- 1 回答
- 0 關(guān)注
- 723 瀏覽
添加回答
舉報
0/150
提交
取消