第56行和第71行,为啥两个类的构造器可以继承Person的构造器,不是只有类才可以继承吗?难道是为了给name赋值吗?而且菱形继承,不是只需要继承中间那两个吗,为啥还把基类继承了??所以,为啥92行代码(以及上面那样最后的逗号)去掉后,编译无法通过呢??
#include <iostream>
#include <string>
class Person
{
public:
Person(std :: string theName);
void introduce();
protected:
std::string name;
};
class Teacher : virtual public Person
{
public:
Teacher(std::string theName, std::string theClass);
void teach();
void introduce();
protected:
std::string classes;
};
class Student : virtual public Person
{
public:
Student(std::string theName, std::string theClass);
void attendClass();
void introduce();
protected:
std::string classes;
};
class TeachingStudent : public Student, public Teacher
{
public:
TeachingStudent(std::string theName, std::string classTeaching, std::string classAttending);
void introduce();
};
Person::Person(std::string theName)
{
name = theName;
}
void Person::introduce()
{
std::cout << "大家好,我是" << name << ".\n\n";
}
Teacher::Teacher(std::string theName, std::string theClass) : Person(theName)
{
classes = theClass;
}
void Teacher::teach()
{
std::cout << name << "教" << classes << ".\n\n";
}
void Teacher::introduce()
{
std::cout << "大家好,我是" << name << ",我在" << classes << "学习.\n\n";
}
Student::Student(std::string theName, std::string theClass) : Person(theName)
{
classes = theClass;
}
void Student::attendClass()
{
std::cout << name << "加入" << classes << "学习.\n\n";
}
void Student::introduce()
{
std::cout << "大家好,我是" << name << ",我在" << classes << "教书.\n\n";
}
TeachingStudent::TeachingStudent(std::string theName,
std::string classTeaching,
std::string classAttending)
:
Teacher(theName, classTeaching),
Student(theName, classAttending),
Person(theName)
{
}
void TeachingStudent::introduce()
{
std::cout << "大家好,我是" << name << ",我教" << Teacher::classes << ",";
std::cout << "同时我再" << Student::classes << "学习.\n\n";
}
int main(void)
{
Teacher teacher("小甲鱼", "C++入门班");
Student student("小乌龟", "C++入门班");
TeachingStudent teachingstudent("小鱼儿", "C++入门班", "c++进阶班");
teacher.introduce();
teacher.teach();
student.introduce();
student.attendClass();
teachingstudent.introduce();
teachingstudent.teach();
teachingstudent.attendClass();
return 0;
};