C ++抽象类:构造函数是或否? [英] C++ Abstract Class: constructor yes or no?

查看:277
本文介绍了C ++抽象类:构造函数是或否?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有一个(或多个)虚拟纯函数的类是抽象的,不能用于创建一个新对象,因此它没有构造函数。

A class with one (or more) virtual pure functions is abstract and it can't used to create a new object so it hasn't a constructor.

现在,我正在读一本有以下例子的书:

Now, I'm reading a book that make the following example:

class Employee {
   public:
       Employee(const char*, const char*);
       ~Employee();
       const char* getFirstName() const;
       const char* getLastName() const;


       virtual double earnings() const=0  // pure virtual => abstract class
       virtual void print() const

  private:
       char* firstName, lastName;
};

如果类是抽象的,为什么我们有一个构造函数?它后来使用这个类(Boss是从Employee派生的):

If the class is abstract why we have a constructor? It use this class later (Boss is public derived from Employee):

void Boss::Boss (const char* first, const char* last, double s)
     : Employee (first, last)

bit confused ...提前感谢

I am a bit confused...thanks in advance

推荐答案

如果你说一个有纯虚函数的类是抽象,不能实例化。但你错了,当你说它不能有一个构造函数。

You're correct when you say that a class that has a pure virtual function is abstract and can't be instantiated. But you're wrong when you say that it can't have a constructor.

确实,如你的例子所示,抽象类可以有私有成员,可能由此类的成员函数使用。这些成员必须初始化。构造函数是一种方法(例如,如第二个示例所示,在派生类中有初始化列表),在我看来比例如 init()函数更好。

Indeed, as your example show, an abstract class can have private members, that may be used by member functions of this class. And these members must be initialized. A constructor is a way to do that (e.g. with initialization list in derived class, as your second sample shows), better in my opinion than an init() function for example.

在答案中编辑我的评论:抽象类可以有成员变量和可能的非虚函数成员函数,

Editing my comment in the answer: An abstract class can have member variables and potentially non-virtual member functions, so that every derived class from the former implements specific features.

然后,这些成员变量初始化的职责可能属于抽象类(至少总是对私有成员

Then, the responsibility for the initialization of these members variables may belong to the abstract class (at least always for private members, because the derived class wouldn't be able to initialize them, yet could use some inherited member functions that may use/rely on these members). Thus, it makes it perfectly reasonable for abstract classes to implement constructors.

这篇关于C ++抽象类:构造函数是或否?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆