假设我有一个基类:
class Animal
{
public:
Animal(double length, double height);
virtual ~Animal();
private:
fLength;
fHeight;
};
构造函数设置fLength = length
和fHeight = height
。
我有一个派生类 Fish
,它工作正常。
但是假设我有一个派生类 Cat
,它有另一个属性 fLegs
需要在构造函数中设置。鱼没有腿,因此 Animal 基类具有属性 fLegs
没有意义。
可以像这样创建 Cat 的构造函数:
猫(双倍长度,双倍高度,双腿)
?
我已经试过了,但出现了一个错误,提示没有匹配的 Animal 函数调用。
有什么方法可以解决这个问题,而无需让 Fish 具有 fLegs 属性并将 Fish 的属性设置为 0?
最佳答案
是的。
例子:
class Animal
{
public:
Animal(double length, double height) : fLength(length), fHeight(height) {}
virtual ~Animal(){};
private:
double fLength;
double fHeight;
};
class Cat : public Animal
{
public:
Cat(double length, double height, double Legs) : Animal(length, height), fLegs(Legs) {}
private:
double fLegs;
};
int main(void)
{
Cat(1,2,4);
return 0;
}
关于c++ - 派生类是否可以具有不在 C++ 中的基类中的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47610312/