c++家庭成员中父亲张大山,民族:汉族,精通计算机和外语;母亲李小曼,民族:侗族,擅长唱歌和跳舞;孩子张小果,民族:侗族,精通计算机和唱歌。编程实现家庭成员的继承关系,并输出家庭成员的相关信息。
时间: 2024-12-21 11:27:58 浏览: 18
在C++中,我们可以使用类和继承的概念来模拟这个家庭成员的关系。首先,我们会创建一个基类`Person`,包含通用的属性如姓名、民族以及技能。然后,为每个特定的家庭成员创建子类,比如`Father`、`Mother`和`Child`,分别继承自`Person`。
```cpp
class Person {
public:
std::string name;
std::string nation;
virtual void displaySkills() = 0; // 虚函数用于展示技能
protected:
Person(const std::string& name, const std::string& nation) : name(name), nation(nation) {}
};
class Father : public Person {
private:
std::string computerSkill;
public:
Father(const std::string& name, const std::string& nation, std::string skill)
: Person(name, nation), computerSkill(skill) {}
void displaySkills() override {
std::cout << "Father (" << name << ") is proficient in computer and speaks foreign languages.\n";
}
};
class Mother : public Person {
private:
std::string singingSkill;
public:
Mother(const std::string& name, const std::string& nation, std::string skill)
: Person(name, nation), singingSkill(skill) {}
void displaySkills() override {
std::cout << "Mother (" << name << ") is skilled in singing and dancing.\n";
}
};
class Child : public Person {
private:
std::string computerSkill; // 孩子也可能有计算机技能
std::string singingSkill;
public:
Child(const std::string& name, const std::string& nation, std::string computerSkill, std::string singingSkill)
: Person(name, nation), computerSkill(computerSkill), singingSkill(singingSkill) {}
void displaySkills() override {
std::cout << "Child (" << name << ") is proficient in computer and singing.\n";
}
};
int main() {
Father father("张大山", "汉族", "外语");
Mother mother("李小曼", "侗族", "唱歌");
Child child("张小果", "侗族", "计算机", "唱歌");
father.displaySkills();
mother.displaySkills();
child.displaySkills();
return 0;
}
```
运行上述程序会输出每个家庭成员的信息和他们的技能。
阅读全文