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

标签 c++ class inheritance

可能是一个非常简单的问题,但我费了好大的劲才弄明白这个问题。我有一个基类:

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 类的名称成员中的值。我如何获得该值?谢谢。

最佳答案

您的函数名称及其功能可以改进。不要将获取和设置成员变量与 cincout 混合使用。我建议按如下方式更改功能。

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/

相关文章:

c# - 为什么抽象类的构造函数应该被保护,而不是公共(public)的?

c++ - 仅由长度为 1 到 10 的两个字母生成所有字符串?

c++ - 将 QGraphicsScene 打印/保存为单色图像质量非常差

c++ - 为什么派生类不能在数组中工作? (C++)

c++ - 编译我的 3 个文件时,我收到错误提示 'operator=' 不匹配

java - Java中synchronized是继承的吗?

c++ - 从文件读取字节为短/长整数

c++ - 如何在所有模板函数实例化中的标签上设置 gdb 断点

java - 使用类名运行 maven 测试 - Maven 如何找到该类?

java - java中不同类对象的数组