c++问题:0x011892AD 处有未经处理的异常(在 Project12.exe 中):

没有错误,但运行时出现问题?求看
#include
using namespace std;
class fruit{
private:
int kind;
int weight;
public:

virtual void loseWeight(){};
virtual int getWeight(){ return weight; };
virtual int getKind(){ return kind; };

};

class apple :public fruit{
private:
int kind;
int weight;
public:
apple(){ kind = 1; weight = 50; };
void loseWeight(){
if ((weight-4) >= 30)
weight -= 4;
else
weight = 30;
}
int getWeight(){
return weight;
}
int getKind(){ return kind; }

};

class orange :public fruit{
private:
int kind;
int weight;
public:
orange(){ kind = 2; weight = 30; }
void loseWeight(){
if ((weight - 4) >= 18)
weight -= 4;
else
weight = 18;
}
int getWeight(){
return weight;
}
int getKind(){ return kind; }

};

class Box{
private:
fruit* f[8];
int a, o,num;
public:
Box(){
a = 0;
o = 0;
num = 0;
for (int j = 0; j < 8; j++)
f[j] = NULL;
}
void put(fruit* k){
if (num < 8){
f[num] = k;
num++;

        if (k->getKind() == 1)a++;
        if (k->getKind() == 2) o++;
    }
    else cout << "已满" << endl;
}

int getApple(){ return a; } //输出盒子中苹果的数量;

int getOrange(){ return o; }        //输出盒子中桔子的数量;

int total(){                        //当前水果总重量
    int w=0;
    for (int i = 0; i < 8; i++){
        if (f[i] != NULL){
            w += f[i]->getWeight();
        }
    }
    return w;
}

int culWeight(){                    
    int w=0;
    for (int i = 0; i < 8; i++){
        if (f[i] != NULL){
            f[i]->loseWeight();
            w += f[i]->getWeight();
        }
    }
    return w;
}

int lost(){                         //一天来盒子中水果减轻的总重量
    return (total() - culWeight());
}

};

void main(){
Box *box=new Box();
fruit *a = new apple();
orange *o=NULL;
cout << a->getKind();
if (a->getKind() == 1) cout << "h";
box->put(a);
box->put(o);
cout << box->getApple() << endl;
cout << box->getOrange() << endl;
box->total();
box->lost();
system("pause");
}

1个回答

你自己单步调试就知道了,错误是这句:box->put(o);
你的o被初始化成NULL,然后进入到put函数里,然后会进行解引用操作,即:k->getKind()
就会产生异常了。
单步调试和设断点调试(VS IDE中编译连接通过以后,按F10或F11键单步执行,按Shift+F11退出当前函数;在某行按F9设断点后按F5执行停在该断点处。)是程序员必须掌握的技能之一。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问