C++类引用的过程是什么?

#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)的调用,所以我想知道的是Drive(const Base& another)函数的具体执行过程???求帮忙解答

潇潇雨雨
浏览 767回答 1
1回答

ibeautiful

lass Drive{private:&nbsp; &nbsp; Base base;public:&nbsp; &nbsp; Drive(const Base& another)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //构造前先默认构造成员变量base,调用Base(int _data = 1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; cout<<"Drive(const Base& another)"<<endl;&nbsp; &nbsp; &nbsp; &nbsp; base = another; //此处调用的是Base& operator=(const Base& another)&nbsp; &nbsp; }};另一种方式,也是高级程序员该用的方式,效率高些:class Drive{private:&nbsp; &nbsp; Base base;public:&nbsp; &nbsp; Drive(const Base& another):base(another) //此处为成员初始化列表,在此处通过拷贝构造直接初始化base,调用Base(const Base& another)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; cout<<"Drive(const Base& another)"<<endl;&nbsp; &nbsp; }};
打开App,查看更多内容
随时随地看视频慕课网APP