2012-02-01 146 views
0

使用类的成员函数访问结构成员内部时出错。你好,我无法弄清我正在得到的运行时错误。
其实我试图t在类中声明一个结构,然后使用主要方法我创建类的指针对象然后使用该对象我试图访问试图初始化结构变量的成员函数。但我没有发生使用类的成员函数访问结构成员内部时出错

class UserInformation 
{ 
public: 
    struct UserInfo 
    { 
     int repu, quesCount, ansCount; 
    }; 


public: 
    void getInfo(int userId) 
    { 
     infoStruct.repu = userId; //here is the error but i cant figure out why 
     next->repu=userId; 
    } 

    void display() 
    { 
     cout<<"display"; 
    } 

    UserInfo infoStruct,*next; 
    int date; 
}; 

int main() 
{ 

    UserInformation *obj; 
    obj->display(); 
    obj->getInfo(23); 
    return 0; 

} 
+0

By * error *,你的意思是编译错误或运行时错误? – 2012-02-01 19:10:49

+0

先生这是一个运行时错误。请帮助! – 2012-02-01 19:24:33

+1

先生,@Oli已经给了你一个答案,这是你解决问题的方法,请按照建议做。 – 2012-02-01 19:27:17

回答

4

此:

UserInformation *obj; 

是一个未初始化的指针。尝试调用成员函数将导致未定义的行为

你可以这样做:

UserInformation *obj = new UserInformation(); 
... 
delete obj; // Remember to clean up! 

但在一般情况下,你应该避免使用原始指针和动态分配的内存(即从new)。

+0

hii oli请尝试在你的编译器上运行上面的代码,请帮助我! – 2012-02-01 19:26:30

+0

感谢oli出色的工作!我无法弄清楚这个愚蠢的错误 – 2012-02-01 19:36:20