【问题标题】:Overridden function does not print base class data重写的函数不打印基类数据
【发布时间】:2020-01-15 20:56:56
【问题描述】:

我的代码中的类继承存在问题。这就是我正在做的事情:我有两个类,一个叫做 Employee,另一个叫做 ManagerEmployee 是基类,它有一个打印名片的函数,包含公司名称和函数name(),即打印员工的姓名。 Manager 类是派生类并继承(公共:Employee)。当我尝试为经理打印同一张名片时,它不显示姓名,只显示公司名称。可能是什么问题呢? 下面是Employee类的小sn-p:

class Employee {

public:
  // Constructor
  Employee(const char* name, double salary) : _name(name), _salary(salary) {}
  Employee() : _name(" "), _salary(0) {} // default constructor
  // Accessors
  const char* name() const { return _name.c_str() ; }
  double salary() const { return _salary ; }
  // Modifyers (if needed)
  double set_salary( double salary) { 
      _salary = salary;
      return _salary;
  }

  // Print functions
  void businessCard(ostream& os = cout) const {
    os << "   +------------------+  " << endl
       << "   | ACME Corporation |  " << endl 
       << "   +------------------+  " << endl
       << "   " << name() << endl ;
  }

private:

  string _name ;
  double _salary ;

} ;



其次,Manager 类:

class Manager : public Employee {

public:

// Constructors
Manager(const char* name, double salary, set<Employee*>& subordinates) : 
    _name(name), _salary(salary), _subs(subordinates) {}

...

// Accessors
const char* name() const { 
    string name;
    name += _name;
    name += " (Manager)"; 
    return name.c_str() ; 
}

void businessCard(ostream& os = cout) const {
    Employee::businessCard();
}

private:
    string _name ;
    double _salary ;
} ;

我认为问题出在 name() 函数中,因为如果我明确地写它,它会出现在卡片上,尽管它不是继承的。 有人可以帮忙吗?

【问题讨论】:

  • 顺便说一句,您应该避免返回name.c_str()name 字符串将在您的 name() 函数结束时被破坏,因此,c_str() 也将无效。理想情况下,不要直接处理普通的char *const char * 类型,尽可能使用std::string
  • @dreamlax,是的,我也更喜欢 string 作为工作类型,但我的练习只是要求 const char*,所以我必须服从!感谢新西兰,你好!
  • 姓名和薪水不应在经理中重新定义。

标签: c++ class inheritance class-hierarchy


【解决方案1】:

当您调用 Employee::businessCard(); 时,它会调用 Employee 类的 const char* name() const { return _name.c_str() ; }。但在构建Manager 对象的早些时候,您还没有将名称传递给基类Employee,因此它没有在Employee 类中设置,并且在打印时将其设置为空。

所以要让它工作,它应该是这样的

Manager(const char* name, double salary, set<Employee*>& subordinates) : Employee(name,salary), _subs(subordinates)

并从管理器中删除 _name_salary 成员变量,因为这违背了本示例中继承的目的。

【讨论】:

  • 谢谢!!!它解决了它!我知道我必须使用 Employee 类中的名称和薪水并在构造函数中声明它,但不知道如何。我只是在“私人”中重新引入变量,重写它们,对吗? :)
  • 如果这个答案解决了它,请考虑适当投票。 :)
  • 它不允许我,我只能作为论坛新手“接受答案”.. :(
猜你喜欢
  • 1970-01-01
  • 2021-03-16
  • 2023-01-04
  • 1970-01-01
  • 2011-05-03
  • 2011-06-17
  • 2023-03-02
  • 2014-06-08
相关资源
最近更新 更多