gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:26:26 24 4
gpt4 key购买 nike

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

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)。

关于c++ - 使用类的成员函数访问内部结构成员时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9101686/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com