打印父函数中子类的数据成员的总和

时间:2017-03-12 20:40:39

标签: c++ class parent

#include <iostream>
using namespace std;


class Fruit {

protected:
int nr_fruits = 0;

public:
void printTotal() {
    cout << "Total fruits in the basket: " << nr_fruits << endl;
}

};


class Mango : public Fruit {

int nr_mangoes;

public:

void getMango(int x) {
    nr_mangoes = x;
    cout << "There are " << nr_mangoes  << " mangoes in the basket" <<  endl;
    nr_fruits = nr_fruits + nr_mangoes;

}
};

class Apple : public Fruit {

int nr_apples;

public:

void getApple(int x) {
    nr_apples = x;
    cout << "There are " << nr_apples << " apples in the basket" <<  endl;
    nr_fruits = nr_fruits + nr_apples;
}
};



int main(int argc, const char * argv[]) {

Apple a1;
Mango m1;

a1.getApple(10);
a1.printTotal();
m1.getMango(20);
m1.printTotal();

return 0;

}

我需要在父类Fruit中创建一个函数,以便能够打印总水果的数量,在我的例子中,nr_mangoes + nr_apples。

显然,按照我这样做的方式,nr_fruits变量只输出芒果量或苹果量作为水果总量。

如何访问子类的数据成员,或者使变量nr_fruits保持整个程序的值。

2 个答案:

答案 0 :(得分:1)

在这种情况下,您需要使用继承。 您将使用虚拟功能。

你必须存储一个指向水果的指针,你所有的水果。

vector<Fruit*> MyFruits;

在类Fruit内,您将实现一个虚函数:

virtual int get_num_of_fruits(){}

在子课内:

int get_num_of_fruits(){
    return nr_child; //nr_apples,nr_mangos etc.
} 

然后你将有int nr_fruits = 0并添加所有水果(苹果,芒果等)的数量。

所以,nr_fruits += MyFruits[i]->get_num_of_fruits(); i = 0i<MyFruits.size()

d,h,b

答案 1 :(得分:1)

对于您的示例而言,为简单起见,您可以将class Fruit { public: static int nr_fruits; void printTotal() { cout << "Total fruits in the basket: " << nr_fruits << endl; } }; int Fruit::nr_fruits = 0; 变量更改为静态,然后在类声明后对其进行初始化:

{{1}}

但是,如果不了解您的计划的全部要求,我认为您可能需要考虑设计一个更好的解决方案...