这是我的代码:
#include <iostream>
#include <string>
using namespace std;
class Sport{
protected:
string name;
double hours;
virtual double returnCalories()=0;
public:
Sport():name("Not defined"),hours(0.0){}
Sport(string n, double c):name(n),hours(c){}
virtual ~Sport(){}
void setName(string x){
name=x;
}
void setTime(double x){
hours=x;
}
};
class Running:public Sport{
public:
static const int CALORIES = 950;
Running(){}
~Running(){}
double returnCalories(){
return hours*CALORIES;
}
};
class Activity{
public:
Sport* one;
Activity(){}
Activity(string n,double time){
one->setName(n);
one->setTime(time);
}
~Activity(){}
};
class Diary{
private:
Activity list_activity[10];
int counter_activity;
public:
Diary():counter_activity(0){}
~Diary(){}
void addActivity(Activity x){
// add activities
}
double sumCalories(){
for(int i=0;i<10;i++){
if(list_activity[i].one->getName()=="Running"){
// I want to call returnCalories() of class Running
}
}
}
};
int main() {
Activity test("Running",3.2);
Diary test2;
test2.addActivity(test);
return 0;
}
现在我有一个问题:
怎么可以在我想要的地方调用类的returnCalories()? (它在代码中评论)
这是否可能,或者我应该以某种方式改变我的逻辑?
答案 0 :(得分:2)
它崩溃了,因为你没有初始化Sport * one;并且您尝试在空指针上调用方法。您需要首先使用&#34; new&#34;在Activity构造函数中创建一个Running对象。像这样的运算符:
one = new Running(n, time);
在&#34; Running&#34;中创建一个重载的构造函数。也采用适当参数的类,以便您可以初始化变量,如上所示。