简体   繁体   English

C ++调用继承的构造函数

[英]C++ calling an inherited constructor

I have a header file, "Item.h", which "Sword.h" inherits, like this: 我有一个头文件“ Item.h”,“ Sword.h”继承了该头文件,如下所示:

#ifndef SWORD_H
#define SWORD_H

#include "Item.h"

class Sword: public Item {
public:
    Sword(int damage);
    ~Sword();
};
#endif

My Item.h is this: 我的Item.h是这样的:

#ifndef ITEM_H
#define ITEM_H

class Item{
public:
   int damage;

   Item(int damage);
   int GetDamage();
};
#endif

And then I have a file, "Sword.cpp", that I want to call the Item constructor from (this is the Item.cpp): 然后,我有一个文件“ Sword.cpp”,我想从中调用Item构造函数(这是Item.cpp):

#include "Item.h"

Item::Item(int damage)
{
   this->damage = damage;
}

int Item::GetDamage()
{
   return damage;
}

I basically want Sword.cpp to be a child class of Item.cpp, so that I can use Item's functions, and set variables such as Damage from Sword.cpp. 我基本上希望Sword.cpp成为Item.cpp的子类,以便我可以使用Item的功能,并设置诸如Sword.cpp中的Damage变量。 I've been told there is no way to inherit constructors in C++ though, so how could I do this? 有人告诉我,没有办法在C ++中继承构造函数,那么我该怎么做呢? Some answers seem to use the explicit keyword, but I can never get it to work. 有些答案似乎使用了显式关键字,但我永远无法使其正常工作。

Any help please? 有什么帮助吗?

You can actually inherit constructors. 您实际上可以继承构造函数。 It is all-or nothing though, you can't select which ones. 它全有-或什么都没有,您不能选择哪个。 This is how you do it: 这是您的操作方式:

class Sword: public Item {
public:
    using Item::Item;
    ~Sword();
};

If you are stuck with a pre-C++11 compiler, then you need to declare the constructor and implement it yourself. 如果您使用的是C ++ 11之前的编译器,则需要声明构造函数并自己实现。 This would be the implementation in Sword.cpp : 这将是Sword.cpp的实现:

Sword::Sword(int damage) : Item(damage) {}

You don't inherit the constructor because the constructor has the same name as the class (and obviously parent and child must have different names). 您不继承构造函数,因为构造函数与类具有相同的名称(并且显然父级和子级必须具有不同的名称)。 But you can use the parent's constructor in the child's constructor 但是您可以在子代的构造函数中使用父代的构造函数

    Sword()
    : Item(3)    // Call the superclass constructor and set damage to 3
    {
        // do something 
    }

You can define the Sword constructor the following way 您可以通过以下方式定义Sword构造函数

Sword(int damage) : Item( damage ) {}

Also it would be better if the destructor of Item were virtual and data member damage should have access control protected. 同样,如果Item的析构函数是虚拟的并且数据成员损坏应具有访问控制保护,那将更好。 For example 例如

class Item{
protected:
   int damage;
public:
   Item(int damage);
   virtual ~Item() = default;
   int GetDamage();
};

您可以像这样从派生类的构造函数调用父级的构造函数:

Sword(int damage): Item(damage) { }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM