调用派生类构造函数中的基类构造函数 [英] calling the base class constructor in the derived class constructor

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

问题描述

我有一个问题:

说我原来有这些类,我不能改变(让我们说他们是从一个图书馆使用):

Say I have originally these classes which I can't change (let's say cause 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天全站免登陆