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

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

问题描述

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

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

我正在阅读一本提供以下示例的书:

I'm reading a book that provides 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 uses this class later (Boss is public derived from Employee):

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

推荐答案

当您说具有纯虚函数的类是抽象的并且无法实例化时,您说得对.但是你说它不能有构造函数就错了.

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 an initialization list in the 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天全站免登陆