对象初始化列表

7月24日上课笔记:

遇到有两个类 Birthday和Student同时都有含参数的构造函数,且在Student类中私有变量为Birthday m_birth;
Birthday(int y, int m, int d);           //有参数的构造参数

 

Birthday.cpp

#include <iostream>

using namespace std;

class Birthday
{
private:
 int m_year;
 int m_month;
 int m_day;
public:
 Birthday(int y, int m, int d);                                   //有参数的构造参数
 void print();
 ~Birthday();
};


Birthday::Birthday(int y, int m, int d)                      //带参构造函数
{
 m_year = y;
 m_month = m;
 m_day = d;
 cout << "Birthday constructor!" << endl;
}

Birthday::~Birthday()                                          //析构函数
{
 cout << "Birthday destruct!" << endl;
}

void Birthday::print()
{
 cout << "birthday:" << m_year << " " << m_month << " " << m_day << endl;
}


class Test
{
private:
 int m_a;
public:
 Test(int a);
 ~Test();
};

Test::Test(int a)                       //带一个参数的构造函数
{
 cout << "Test constructor!" << endl;
 m_a = a;
}

Test::~Test()
{
 cout << "Test destruct!" << endl;
}

class Student
{
private:
 Birthday m_birth;                        //对象作为私有变量
 Test t;
 char name[20];
 const int age;
public:
 Student(char *n, int y, int m, int d);     //这里的参数要包括Birthday构造函数里的参数,即y,m,d
 void print();
 ~Student();
};


Student::Student(char *n, int y, int m, int d):m_birth(y, m, d),age(20),t(d)   

//对象初始化列表Student参数中的y,m,d是给了Birthday中的构造函数的参数
{
 cout << "Student constructor!" << endl;
 strcpy(name, n);
}

Student::~Student()
{
 cout << "Student destruct!" << endl;
}

void Student::print()
{
 
 cout << "name:" << name << endl;
 cout << "age:" << age << endl;
 m_birth.print();
 
}

int main()
{
 Student s1("zys",1998,1,1);
 s1.print();
 return 0;
}

 

构造函数的调用顺序与初始化列表顺序无关,跟对象声明的顺序有关

执行结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值