【问题标题】:Error accessing structure member inside using member function of class使用类的成员函数访问内部结构成员时出错
【发布时间】:2012-02-01 19:07:34
【问题描述】:

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

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;

}

【问题讨论】:

  • error是指编译错误还是运行时错误?
  • 先生这是一个运行时错误。请帮忙!!
  • 先生,@Oli 已经给了您答案,这是您问题的解决方案,请按照建议进行。

标签: c++ class function struct member


【解决方案1】:

这个:

UserInformation *obj;

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

你可以这样做:

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

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

【讨论】:

  • hii oli 请尝试在您的编译器上运行上述代码,请帮助我!!
  • 感谢 oli 出色的工作!!我无法弄清楚这个愚蠢的错误
猜你喜欢
  • 2016-11-14
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 2013-05-31
  • 2017-06-11
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
相关资源
最近更新 更多