-4

所以根据下面的评论,我想确认这段代码是非法的,原因包括:

  1. 我们从抽象类 Employee 创建了一个对象 joe
  2. 由于没有定义 printCheck(),它使 HourlyEmployee 成为像 Employee 一样的抽象类。因此,我们从一个抽象类中创建了对象 joe。

?

class Employee
{
public:
  Employee();
  Employee(const string& theName, const string& theSsn);
  string getName() const;
  string getSsn() const;
  double getNetPay() const;
  void setName(const string& newName);
  void setSsn(const string& newSsn);
  void setNetPay(double newNetPay);
  virtual void printCheck() const = 0;
private:
  string name;
  string ssn;
  double netPay;
};


class HourlyEmployee : public Employee
{
public: 
  HourlyEmployee(); 
  //<Some more legal member function definitions, none of which are 
  //pure virtual functions.> 
private: 
  double wageRate;
  double hours;
};


int main( )
{
  Employee joe; 
  joe = HourlyEmployee();
}
4

2 回答 2

2

违法的是:

Employee 是一个抽象基类。这一行:

Employee joe;

本身是非法的,它正在创建您的抽象类的实例。

joe = HourlyEmployee();

即使这些类都是完整的,因为它会切片,这也是一个坏主意。joe 是一个对象,而不是一个引用。

如果 HourlyEmployee 仍然是抽象的(不实现 printCheck()),那么您的行当然是非法的,因为您正在创建一个的(临时)实例。

Incidentally if both classes were complete, thus the code compiled, but printCheck() remained virtual (not pure), then

joe.printCheck();

would invoke the Employee version not the HourlyEmployee version because joe is of type Employee and remains so in spite of the assignment. That is why slicing is mostly a bad idea.

于 2012-12-17T11:28:50.077 回答
1

HourlyEmployee class needs to implements printCheck() function of the base class. Once you implement this function, HourlyEmployee is a objectable class.

于 2012-12-17T12:13:22.343 回答