初识C++继承

先是自己凭借自己在课堂上的记忆打了一遍。自然出了错误。

//编译错误
#include <iostream>
#include <cstdlib>
using namespace std;

class people
{
	private:
		int age;
		int sex; // 1 -girl 2 -boy
	public:
		people(int a = 0, int b = 0): age(a), sex(b){};
};

class student : public people
{
	private:
		int num;
		int score;
		string name;
	public:
		student(int bnum = 0, int bscore = 0, int bage = 0, int bsex = 0, string bname):people(bage, bsex) //错误
		{
			num = bnum;
			score = bscore;
			name = bname;
		};
		
		void display();
};

void student::display()
{
	if(sex == 1) //错误
	cout << name << " girl " << num << " " << age << " " << score << endl;
	else 
	cout << name << " boy " << num << " " << age << " " << score << endl;
}

int main()
{
	student Liming(10001, 100, 20, 2, "李鸣");
	Liming.display() ;
	
	return 0;
}
错误小结:
    1.类student是public继承于类people,那么在student的成员函数中,无法访问父类的private和protected属性的成员,只能通过继承过来的父类的成员函数访问它们。
    2.初始化列表写错了。函数的默认参数最后一句 string bname; 应该是 string bname = "";

改了之后,可以运行了。

#include <iostream>
#include <cstdlib>
using namespace std;

class people
{
	private:
		int age;
		int sex; // 1 -girl 2 -boy
	public:
		people(int a = 0, int b = 0): age(a), sex(b){};
		int getage();
		int getsex();
};

int people::getage()
{
	return age;
}

int people::getsex()
{
	return sex;
}

class student : public people
{
	private:
		int num;
		int score;
		string name;
	public:
		student(string bname,int bnum = 0, int bscore = 0, int bage = 0, int bsex = 0)
		:people(bage, bsex),num(bnum),score(bscore){name = bname;};
		
		void display();
};

void student::display()
{
	if(getsex() == 1)
	cout << name << " girl " << num << " " << getage() << " " << score << endl;
	else 
	cout << name << " boy " << num << " " << getage() << " " << score << endl;
}

int main()
{
	student Liming("李鸣", 10001, 100, 20, 2);
	Liming.display() ;
	
	return 0;
}

学习到的知识点:

1.对于父类的派生类来说,其对象的初始化需要利用初始化列表进行操作。比如:

student(string bname, int bnum = 0, int bscore = 0, int bage = 0, int bsex = 0)
:people(bage, bsex),num(bnum),score(bscore){name = bname;};

上面的语句调用了父类的初始化构造函数,所以父类的构造函数应具有含参构造函数,可以利用重载来实现。
个人的习惯是:写一个含有默认参数的初始化列表。

2.如果是public继承,那么在派生类的成员函数中无法访问其从父类继承过来的具有private和protected属性的成员。
这个时候,可以通过调用从父类继承过来的成员函数获取其值。例如:

int people::getage()
{
	return age;
}

int people::getsex()
{
	return sex;
}

···

void student::display()
{
	if(getsex() == 1) //调用父类的成员函数
	cout << name << " girl " << num << " " << getage() << " " << score << endl;
	else 
	cout << name << " boy " << num << " " << getage() << " " << score << endl;
}

3.复习了一下含有默认参数的构造函数,设置默认参数时应从右向左。例如:
student(int bnum = 0, int bscore = 0, int bage = 0, int bsex = 0, string bname):people(bage, bsex) //错误
应为:
student(int bnum = 0, int bscore = 0, int bage = 0, int bsex = 0, string bname = ""):people(bage, bsex)
原文地址:https://www.cnblogs.com/qq952693358/p/5572708.html