简体   繁体   中英

C++ Derived Class Accessing Base Class member

Probably a very simple question, but I'm having a devil of a time figuring this out. I have a base class:

class User
{
    public:
      User();
      ~User();
      void GetUser();
      void SetUser();
    protected:
      std::string name;
};

Here's my derived class:

class UserInfo: public User
{
  public:
    void GetUser();
};

And the methods:

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: ";
}

Everything seems to work fine, but when I call UserInfo::GetUser() from the program, it doesn't execute or retrieve the value stored in the name member of the User class. How do I get that value? Thanks.

Your function names and what they do can be improved. Don't mix getting and setting member variables with cin or cout . I suggest changing the functions as follows.

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;
};

and implement them as:

std::string const& User::GetName() const
{
  return name;
}

void User::SetName(std::string const& newName)
{
  name = newName;
}

After that, you don't need the GetUser member function in UserInfo .

When you are ready to set the name of a User , use:

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

This allows you to separate the setting of the name of a User from where you get that name from.

When you are ready to print the name a User , use:

std::cout << u.GetName();

This allows you to separate the getting of the name of a User from how you use the name after you get it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM