首页 > 编程语言 > 详细

c++使用初始化列表来初始化字段

时间:2019-07-13 23:15:19      阅读:118      评论:0      收藏:0      [点我收藏+]
#include<iostream>
using namespace std;

class Student1
{
private:
	int _a;
    int _b;

public:
    void
    fprint()
    {
        cout << " a = " << _a << " " << "b = " << _b << endl;
    }

    //Student1(int i):b(i),a(b){ }    //异常顺序:发现a的值为0  b的值为2  说明初始化仅仅对b有效果,对a没有起到初始化作用
    
	Student1(int a, int b): _a(a), _b(b) 
	{ 
		cout << "constructor" << endl;
	} //正常顺序:发现a = b = 2 说明两个变量都是初始化了的

    Student1()                         // 无参构造函数
    {
        cout << "默认构造函数Student1" << endl ;
    }

    Student1(const Student1 &t1) //拷贝构造函数
    {
        cout << "拷贝构造函数Student1" << endl ;
        this->_a = t1._a;
		this->_b = t1._b;
    }

    Student1 &
    operator = (const Student1 &t1) // 赋值运算符
    {
        cout << "赋值函数Student1" << endl ;
        this->_a = t1._a ;
		this->_b = t1._b ;
        return *this;
    }

};

class Teacher
{
public:
    Student1 test;	//类中包含类
    Teacher(Student1 &t1)
    {
        test  = t1 ;
    }
};

int main(void)
{
    Student1 A(2,4);      //进入默认构造函数
    Teacher B(A);        //进入拷贝构造函数
    A.fprint();           //输出前面初始化的结果
	B.test.fprint();
}

  

c++使用初始化列表来初始化字段

原文:https://www.cnblogs.com/CodeWorkerLiMing/p/11182200.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!