我正在尝试获取函数membername
以返回字符串staffmember
,而usermember
使用数据类型字符串是不可能的吗?如果没有,我可以使用其他数据类型吗?
string membername();
{
if (member == 1)
{
string studentmember;
cout << "Enter Student Member Name (possible names: Tom, Max, Ben): ";
cin >> studentmember;
return studentmember;
}
if (member == 2)
{
string staffmember;
cout << "Enter Staff Member Name (possible names: Linda, Mary, Bob): ";
cin >> staffmember;
return staffmember;
}
else
{
cout << "Enter a valid number" << endl;
}
}
答案 0 :(得分:1)
您可以执行以下操作:
struct Person
{
int id; // Every person has an ID.
std::string name; // Every person has a name.
// Every Person has a function to input their name,
// implemented (specialized) by the child.
virtual void get_name() = 0;
};
struct Student : public Person // A student is-a person
{
void get_name()
{
std::cout << "Enter Student's name:";
std::getline(std::cin, name);
}
};
struct Staff : public Person // A staff member is-a person
{
void get_name()
{
std::cout << "Enter Staff's name:";
std::getline(std::cin, name);
}
};
学生对象和职员对象具有不同的get_name
方法。
您可以将它们作为一个人来对待:
Person * p1 = new Student;
Person * p2 = new Staff;
p1->get_name(); // Get the name of the person, using appropriate prompt.
p2->get_name(); // Uses the Staff::get_name() function.
对于模板版本,您必须使用用于人员类型的方法(或成员)。
template <typename College_Person>
void get_name(College_Person& cp)
{
const std::string person_type_name = cp.get_type_name();
std::cout << "Enter " << person_type_name << " name: ";
std::getline(std::cin, cp.name);
}
或
template <typename College_Person>
void get_name(College_Person& cp)
{
std::cout << "Enter "
<< cp.person_type_name
<< " name: ";
std::getline(std::cin, cp.name);
}