Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;派生类访问基类成员_C++_Class_Inheritance - Fatal编程技术网

C++ C++;派生类访问基类成员

C++ C++;派生类访问基类成员,c++,class,inheritance,C++,Class,Inheritance,可能是一个很简单的问题,但我花了很长时间才弄明白。我有一个基本类: class User { public: User(); ~User(); void GetUser(); void SetUser(); protected: std::string name; }; 这是我的派生类: class UserInfo: public User { public: void GetUser(); }; 方法

可能是一个很简单的问题,但我花了很长时间才弄明白。我有一个基本类:

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: ";
}
User::User()
{
name=“”;
}
void User::GetUser()
{
姓名;
}
用户::~User()
{
name=“”;
}
void UserInfo::GetUser()
{

cout您的函数名及其功能可以改进。不要将获取和设置成员变量与
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);
std::cout << u.GetName();
这允许您将
用户
的名称设置与从中获取该名称的位置分开

当您准备好打印用户姓名时,请使用:

User u;
std::string name;
std::cin >> name;
u.SetName(name);
std::cout << u.GetName();

std::难道显示的代码没有明显的错误(好吧,没有任何与所述问题直接相关的问题)。因此,问题一定在未显示的代码中。显示调用GetUser()的代码。也许您希望使用
virtual void GetUser();
而不是
void GetUser()
在类中
用户
。感谢您的帮助!意识到基于所有建议,我试图使用错误的方法调用。