gpt4 book ai didi

c++ - 如何继承方法然后向它们添加一些东西?

转载 作者:太空宇宙 更新时间:2023-11-04 12:42:18 26 4
gpt4 key购买 nike

class uni_person {
public:
string f_name; // 1
string s_name; // 2
int age; // 3
string institute;// 5
string uni; // 6
string p_number; // 7

void addSmth() {
int x;
cout << "What do you want to add about the student ?\n1: first name\n2: second name\n3: age\n4: course\n5: institute\n6: university\n7: phone number\n8: group\n";
cin >> x;
switch (x) {
case 1: cin >> f_name; break;
case 2: cin >> s_name; break;
case 3: cin >> age; break;
case 5: cin >> institute; break;
case 6: cin >> uni; break;
case 7: cin >> p_number; break;
default: cout << "Error" << endl; break;
}
}
};

class Student: public uni_person {
public:
int course;
int group;

void addSmth() {
int x;
cout << "What do you want to add about the student ?\n1: first name\n2: second name\n3: age\n4: course\n5: institute\n6: university\n7: phone number\n8: group\n";
cin >> x;
switch (x) {
case 4: cin >> course; break;
case 8: cin >> group; break;
}
}
};

所以我有一个问题,我目前正在学习 C++ 中的 OOP,我遇到了这个问题......如何让类继承其他类的方法并向其添加新的东西而不重写它?它有什么特殊功能吗?我重写了 addSmth() 并想向 addSmth() 添加更多行为。

最佳答案

首先,您应该将用户交互与实际逻辑分开。如果你有,你可以从 Derived 函数显式调用 Base 函数:

您还应该将基函数标记为 virtual 并将派生函数标记为 override

virtual void uni_person::promptAddSmth()
{
cout << "What do you want to add about the student ?\n1: first name\n2: second name\n3: age\n4: course\n5: institute\n6: university\n7: phone number\n8: group\n";
int x;
cin >> x;
addSmth(x);
}

virtual void uni_person::addSmth(int x)
{
switch (x) {
case 1: cin >> f_name; break;
case 2: cin >> s_name; break;
case 3: cin >> age; break;
case 5: cin >> institute; break;
case 6: cin >> uni; break;
case 7: cin >> p_number; break;
default: cout << "Error" << endl; break;
}
}

void Student::promptAddSmth() override
{
cout << "What do you want to add about the student ?\n1: first name\n2: second name\n3: age\n4: course\n5: institute\n6: university\n7: phone number\n8: group\n";
int x;
cin >> x;
addSmth(x);
}

void Student::addSmth(int x) override
{
switch(x) {
case 4: cin >> course; break;
case 8: cin >> group; break;
default: uni_person::addSmth(x); break;
}
}

关于c++ - 如何继承方法然后向它们添加一些东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53592209/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com