C++笔记(十九)私有继承和多重继承
程序员文章站
2022-03-01 14:50:50
...
//Student.h
/*
私有继承:使用私有继承,基类的共有成员和保护成员都将成为派生类的私有成员
多重继承:表示可以有多个基类。
*/
#ifndef STUDENT
#define STUDENT
#include<iostream>
#include<string>
#include<array>
using std::string;
using std::cout;
using std::endl;
using std::array;
//名称类
class Name
{
protected:
string name;
public:
Name();
Name(string namep);
string getName();
};
//分数类
class Score
{
protected:
array<double,3> scores;
public:
Score();
Score(double score0, double score1, double score2);
array<double, 3> getScores();
};
class Student : private Name,private Score //私有多重继承
{
public:
Student();
Student(string namep,double score0, double score1, double score2 );
~Student();
friend std::ostream & operator<<(std::ostream &os, const Student &stu);
};
#endif // !STUDENT
//student.cpp
#include "Student.h"
Name::Name() {
name = "none";
}
Name::Name(string namep) {
name = namep;
}
string Name::getName() {
return name;
}
Score::Score() {
scores[0] = 0.0;
scores[1] = 0.0;
scores[2] = 0.0;
}
Score::Score(double score0, double score1, double score2) {
scores[0] = score0;
scores[1] = score1;
scores[2] = score2;
}
array<double, 3> Score::getScores() {
return scores;
}
Student::Student():Name(),Score()
{
}
Student::Student(string namep, double score0, double score1, double score2):Name(namep),Score(score0,score1,score2) {
}
Student::~Student()
{
}
std::ostream & operator<<(std::ostream &os, const Student &stu) {
cout << "name:" << stu.name << " scores:" << stu.scores[0] << "," << stu.scores[1] << "," << stu.scores[2] << endl;
return os;
}
int main() {
Student stu = Student("yueer",90.1,95.5,100);
cout << stu << endl;
//stu.getName(); 私有继承后外部不可访问基类中的成员函数
return 0;
}
输出结果:
name:yueer scores:90.1,95.5,100
上一篇: No such file or directory
下一篇: C++私有继承