对象初始化列表

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;
}

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

执行结果:

猜你喜欢

转载自blog.csdn.net/zys15195875600/article/details/81199145