为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C++
潇潇雨雨 2018-06-25 00:00:15
#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)函数的具体执行过程???求帮忙解答
查看完整描述

1 回答

?
ibeautiful

TA贡献1993条经验 获得超5个赞

lass Drive

{

private:

    Base base;

public:

    Drive(const Base& another)

    {

        //构造前先默认构造成员变量base,调用Base(int _data = 1)

         

        cout<<"Drive(const Base& another)"<<endl;

        base = another; //此处调用的是Base& operator=(const Base& another)

    }

};

另一种方式,也是高级程序员该用的方式,效率高些:


class Drive

{

private:

    Base base;

public:

    Drive(const Base& another):base(another) //此处为成员初始化列表,在此处通过拷贝构造直接初始化base,调用Base(const Base& another)

    {

        cout<<"Drive(const Base& another)"<<endl;

    }

};


查看完整回答
反对 回复 2018-08-25
  • 1 回答
  • 0 关注
  • 695 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信