相关疑难解决方法(0)

从派生类构造函数中调用基类构造函数

我有个问题:

说我原来这些我无法改变的课程(让我们说它们来自我正在使用的图书馆):

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];
}
Run Code Online (Sandbox Code Playgroud)

但后来我需要一个我只添加几个字段的类,所以我这样做了:

class PetStore : public Farm
{
public :
    PetStore()
    {
     idF=0;
    };
private:
    int idF;
    string nameF;
}
Run Code Online (Sandbox Code Playgroud)

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

c++ inheritance constructor visibility derived-class

27
推荐指数
3
解决办法
13万
查看次数

为什么复制构造函数不像默认构造函数或析构函数那样"链接"?

这可能是一个明显答案或重复的问题.如果有,抱歉,我会删除它.

为什么不复制构造函数(如默认ctors或dtors),以便在调用派生类的复制构造函数之前调用基类的复制构造函数?对于复制构造函数和析构函数,它们分别在从base-to-derived和derived-to-base的链中被调用.为什么复制构造函数不是这种情况?例如,这段代码:

class Base {
public:
    Base() : basedata(rand()) { }

    Base(const Base& src) : basedata(src.basedata) {
        cout << "Base::Base(const Base&)" << endl;
    }

    void printdata() {
        cout << basedata << endl;
    }

private:
    int basedata;
};

class Derived : public Base {
public:
    Derived() { }

    Derived(const Derived& d) {
        cout << "Derived::Derived(const Derived&)" << endl;
    }
};


srand(time(0));


Derived d1;      // basedata is initialised to rand() thanks to Base::Base()

d1.printdata();  // prints the random number

Derived d2 = …
Run Code Online (Sandbox Code Playgroud)

c++ constructor copy-constructor

19
推荐指数
1
解决办法
9533
查看次数