初始化顺序
(1).父类初始化(父类的父类初始化等等)
(2).类对象数据成员初始化(如果作为数据成员的类对象没有无参构造函数,则要在本类的构造参数列表中显示调用有参构造函数来初始化)
(3).子类的初始化(分别调用各自的构造器)
顺序产生原因:父类的构造函数和类对象数据成员的构造函数在本类的构造参数列表中被默认调用来初始化对应的数据(前提是父类、类对象的类都有默认的构造函数),因为构造参数列表会快于本类的构造函数调用,所以产生这个顺序
主函数:
#include "stdafx.h"
#include <iostream>
using namespace std;
#include "student.h"
#include "Graduate.h"
#include "Doctor.h"
int _tmain(int argc, _TCHAR* argv[])
{
Student s("zhaosi", 34, 222);
s.dis();
cout << "=========================" << endl;
Graduate g("liuneng", 33, 333, 3000, 1999, 9, 9);//可以断点查看
g.print();
g.getBirthday();
cout << "=========================" << endl;
Doctor d("bigHead", 44, 444, 4000, 1999, 9, 9, "doctor Liu");
d.dump();
return 0;
}
Student.h
#pragma once
#include <iostream>
using namespace std;
#include <string>
class Student
{
public:
Student(string sn, int ia, float fs);
void dis();
private:
string name;
int age;
float score;
};
Student.cpp
#include "Student.h"
Student::Student(string sn, int ia, float fs)
:name(sn), age(ia), score(fs)
{
}
void Student::dis()
{
cout << "name: " << name << endl;
cout << "age: " << age << endl;
cout << "score: " << score << endl;
}
Graduate.h
#pragma once
#include "Student.h"
#include "Birthday.h"
class Graduate :public Student
{
public:
Graduate(string sn, int ia, float fs,
double ds, int iy, int im, int id);
void print();
void getBirthday();
private:
double salary;
Birthday birth; //类对象
};
Graduate.cpp
#include "Graduate.h"
Graduate::Graduate(string sn, int ia, float fs,
double ds, int iy, int im, int id)
:Student(sn, ia, fs), birth(iy, im, id)
//初始化写在参数列表里面 通过调用父类构造器的方式
{
//birth 为类对象的初始化
salary = ds;
}
void Graduate::print()
{
dis(); //dis为public的
cout << "salary: " << salary << endl;
}
void Graduate::getBirthday()
{
birth.dis();
}
Doctor.h
#pragma once
#include "Graduate.h"
class Doctor :public Graduate
{
public:
Doctor(string sn, int ia, float fs, double ds,
int iy, int im, int id, string st);
void dump();
private:
string title;
};
Doctor.cpp
#include "Doctor.h"
Doctor::Doctor(string sn, int ia, float fs, double ds,
int iy, int im, int id, string st)
:Graduate(sn, ia, fs, ds, iy, im, id), title(st)
{
}
void Doctor::dump()
{
print();
cout << "title: " << title << endl;
}