子类的初始化顺序

初始化顺序 
(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;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值