第一次发帖,请教一个C++问题!!!
先贴代码:
[code=C/C++][/code]
#include<iostream>
#include<string>
#include <cassert>
using namespace std;
static int SMALL_FOOD = 1;
static int BIG_FOOD = 2;
static int WEST = 3;
static int EAST = 4;
struct _Visitor;
//
typedef struct _Tofu
{
int type;
void (*eat)(struct _Tofu* pTofu,struct _Visitor* pVisitor);
}Tofu;
//
typedef struct _Visitor
{
int region;
void (*process)(struct _Tofu* pTofu,struct _Visitor* pVisitor);
}Visitor;
void eat(struct _Tofu* pTofu,struct _Visitor* pVisitor)
{
assert(pTofu != NULL && pVisitor != NULL);
pVisitor->process(pTofu,pVisitor);
}
void process(struct _Tofu* pTofu,struct _Visitor* pVisitor)
{
assert(NULL != pTofu && NULL != pVisitor);
if( (pTofu->type == SMALL_FOOD && pVisitor->region == WEST) ||
(pTofu->type == BIG_FOOD && pVisitor->region == EAST) )
{
cout<<"I like this food !\n";
return;
}
cout<<"I do not like this food ! \n";
}
int main()
{
Visitor* pVis;
pVis->region = EAST;//请问这个为什么有问题,编译通过,运行出错!
//
Visitor vis;
vis.region = EAST; //没问题
return 0;
}
[解决办法]
Visitor* pVis; 声明了 但是没初始化,没分配空间
[解决办法]
Visitor* pVis;
明显指针没有初始化,指向了不可写区域,导致出错