从派生类构造函数中调用基类构造函数 [英] Calling the base class constructor from the derived class constructor

查看:179
本文介绍了从派生类构造函数中调用基类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题:

说我最初这些课程是我无法改变的(让我们说因为它们来自我所在的图书馆使用):

Say I have originally these classes which I can't change (let's say because they're taken from a library which I'm using):

class Animal_
{
public:
    Animal_();
    int getIdA()
    {
        return idA;
    };
    string getNameA()
    {
        return nameA;
    }
private:
    string nameA;
    int idA;
}

class Farm
{
public :
    Farm()
    {
        sizeF=0;
    }
    Animal_* getAnimal_(int i)
    {
        return animals_[i];
    }
    void addAnimal_(Animal_* newAnimal)
    {
        animals_[sizeF]=newAnimal;
        sizeF++;
    }

private:
    int sizeF;
    Animal_* animals_[max];
}

但是我需要一个我只添加几个字段的课程,所以我做了这个:

But then I needed a class where I just add couple of fields so I did this:

class PetStore : public Farm
{
public :
    PetStore()
    {
     idF=0;
    };
private:
    int idF;
    string nameF;
}

但是我无法初始化我的派生类,我的意思是我做了这个继承所以我可以添加动物到我的PetStore,但现在因为sizeF是私人的我怎么能这样做?我想也许在PetStore默认构造函数中我可以调用Farm()...所以任何想法?

But I can't initialize my derived class, I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that? I'm thinking maybe in the PetStore default constructor I can call Farm()... so any idea?

推荐答案

构造函数 PetStore 将调用 Farm 的构造函数;有
你无法阻止它。如果你什么都不做(就像你做的那样),它将
调用默认构造函数( Farm());如果你需要传递参数,
你必须在初始化列表中指定基类:

The constructor of PetStore will call a constructor of Farm; there's no way you can prevent it. If you do nothing (as you've done), it will call the default constructor (Farm()); if you need to pass arguments, you'll have to specify the base class in the initializer list:

PetStore::PetStore()
    : Farm( neededArgument )
    , idF( 0 )
{
}

(类似地, PetStore 的构造函数将调用
的构造函数 nameF 。类总是的构造函数调用
的所有基类及其所有成员的构造函数。)

(Similarly, the constructor of PetStore will call the constructor of nameF. The constructor of a class always calls the constructors of all of its base classes and all of its members.)

这篇关于从派生类构造函数中调用基类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆