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

#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();
}

  

转载于:https://www.cnblogs.com/CodeWorkerLiMing/p/11182200.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值