使用类的成员函数访问内部的结构成员时出错

Error accessing structure member inside using member function of class

本文关键字:成员 结构 出错 内部 函数 访问      更新时间:2023-10-16

使用类的成员函数访问内部结构成员时出错。你好,我无法找出我遇到的运行时错误
实际上,我试图在类内声明一个结构,然后使用主方法创建该类的指针对象,然后使用该对象访问试图初始化结构变量的成员函数。但不会发生

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;
}

这:

UserInformation *obj;

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

你可以这样做:

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

但一般来说,您应该避免使用原始指针和动态分配的内存(即来自new)。