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. This would be the implementation in Sword.cpp
:
Sword::Sword(int damage) : Item(damage) {}
-------------------생성자가 클래스와 이름이 같기 때문에 생성자를 상속하지 않습니다 (분명히 부모와 자식은 다른 이름을 가져야합니다). 하지만 자식 생성자에서 부모 생성자를 사용할 수 있습니다.
Sword()
: Item(3) // Call the superclass constructor and set damage to 3
{
// do something
}
-------------------다음과 같은 방법으로 Sword 생성자를 정의 할 수 있습니다.
Sword(int damage) : Item( damage ) {}
또한 Item의 소멸자가 가상이고 데이터 구성원 손상이 액세스 제어를 보호해야하는 경우 더 좋을 것입니다. 예를 들면
class Item{
protected:
int damage;
public:
Item(int damage);
virtual ~Item() = default;
int GetDamage();
};
-------------------다음과 같이 파생 클래스의 생성자에서 부모의 생성자를 호출 할 수 있습니다.
Sword(int damage):
Item(damage)
{
}
출처
https://stackoverflow.com/questions/22079994