C++,初始化列表

初始化列表:
  // 特点:是一种便捷的初始化成员变量的方式,初始化顺序只跟成员变量的声明顺序有关,只能用到构造函数中
   // 构造函数调用构造函数必须在构造函数初始化列表中调用
   struct Person {
       int m_age;
       int m_height;
       int m_weight;
       Person(){
           this->m_age = 0;
           this->m_height = 0;
       }
   
   Person(){
       cout << "Person()" << this << endl;
       Person(0,0);调用相等于下面的汇编代码
       // 直接调用构造函数,会创建一个临时对象,传入一个临时的地址值给this指针,汇编如下面
   // 汇编伪代码:
       Person temp;
       temp.Person(0,0);
   }
   
       Person():Person(0,0){
       }
   
   
       // 初始化列表:m_age(age),m_height(height),等价于下面的构造函数
       Person(int age,int height):m_age(age),m_height(height){
       }
   
       Person(int age,int height){
           this->m_age = age;
           this->m_height = height;
   
   // 汇编语言:
      mov eax,dword ptr [this]
      mov ecx,dword ptr [age]
      mov dword ptr [eax], ecx
   
   
       mov eax,dword ptr [this]
       mov ecx,dword ptr [height]
       mov dword ptr [eax+4], ecx
       }
   
       void display(){
           cout << "m_age is" << this->m_age << endl;
           cout << "m_height is" << this->m_height << endl;
       }
   };
   
   int main(){
       Person person1;// 构造函数是在对象分配内存以后才调用的构造函数,构造函数也是属于这个类的成员函数person1.Person(),会把person1对象的地址值传给构造函数的this指针
   // 汇编语言:
   lea ecx, [ebp-10h] // ebp-10h是person对象的地址值
   
   
   
       Person person2(10,20);
       person.m_no = 20;
   
       getchar();
       return 0;
   }
   
   
   
   //构造函数的相互调用
   struct Person {
       int m_age;
       int m_height;
       Person():Person(0,0){}
       Person(int age,int height):m_age(age),m_height(height){}
   }
   
   // 注意:下面的写法是错误的,初始化的是一个临时对象
   struct Person{
       int m_age;
       int m_height;
       Person():Person(0,0){
            Person(0,0);
       }
       Person(int age,int height):m_age(age),m_height(height){}
   }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值