可能是一个非常简单的问题,但我费了好大的劲才弄明白这个问题。我有一个基类:
class User
{
public:
User();
~User();
void GetUser();
void SetUser();
protected:
std::string name;
};
这是我的派生类:
class UserInfo: public User
{
public:
void GetUser();
};
和方法:
User::User()
{
name = "";
}
void User::GetUser()
{
cout << name;
}
void User::SetUser()
{
cin >> name;
}
User::~User()
{
name = "";
}
void UserInfo::GetUser()
{
cout << " ";
User::GetUser();
cout << ", you entered: ";
}
一切似乎都工作正常,但是当我从程序中调用 UserInfo::GetUser() 时,它不会执行或检索存储在 User 类的名称成员中的值。我如何获得该值?谢谢。
最佳答案
您的函数名称及其功能可以改进。不要将获取和设置成员变量与 cin
或 cout
混合使用。我建议按如下方式更改功能。
class User
{
public:
User();
~User();
// Make the Get function a const member function.
// Return the name.
std::string const& GetName() const;
// Take the new name as input.
// Set the name to the new name.
void SetName(std::string const& newName);
protected:
std::string name;
};
并将它们实现为:
std::string const& User::GetName() const
{
return name;
}
void User::SetName(std::string const& newName)
{
name = newName;
}
之后,就不需要UserInfo
中的GetUser
成员函数了。
当您准备好设置用户
的名称时,请使用:
User u;
std::string name;
std::cin >> name;
u.SetName(name);
这允许您将 User
名称的设置与获取该名称的位置分开。
当您准备打印名称User
时,请使用:
std::cout << u.GetName();
这允许您将获取用户
的名称与获取名称后如何使用该名称分开。
关于C++派生类访问基类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41798820/