c++ : code explanation for method prototype with const = 0

有些话、适合烂在心里 提交于 2020-07-15 01:00:10

问题


I hava a class declaration with a piece of code that I do not understand :

class Weapon
{
  public:
    virtual void attack() const = 0;
};

What does the const = 0 part means ?


回答1:


This is a pure virtual method (=0) which is not supposed to change the data of the class (const). You should provide an implementation in one of the classes deriving from Weapon! See this: Difference between a virtual function and a pure virtual function

You are expected to derive from the Weapon (can be considered interface) concrete classes, such as Axe , Shotgun, etc ... where you will provide the attack() method.




回答2:


Putting const after a member function indicates that the code inside it will not modify the containing object (except in the case of mutable members). This is useful because the compiler will report an error if you accidentally modify the object when you didn't intend to.

The = 0 is not related to const. It's used in conjunction with virtual to indicate that the function is pure virtual. That means it must be overridden by a sub-class. Classes containing pure virtual functions are sometimes described as abstract because they cannot be directly instantiated.

Using your example, you would not be able to create an object of type Weapon, because the attack() function is not defined. You would have to create a sub-class, such as:

class Sword : public Weapon
{
public:
    void attack() const
    {
        // do something...
    }
};


来源:https://stackoverflow.com/questions/21187965/c-code-explanation-for-method-prototype-with-const-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!