Class数组引用的NullReferenceException

Jer*_*ngo -1 c++ class instance nullreferenceexception

我的代码如下:

int main()
{ 
    CProfile **profiles;
    *profiles  = new CProfile[8];
    profiles[0] = new CProfile(2000,2,4);
    profiles[1] = new CProfile(55000,6,50);
    profiles[2] = new CProfile(758200,5,23);
}
Run Code Online (Sandbox Code Playgroud)

CProfile定义为:

#ifndef PROFILE_H
#define PROFILE_H

class CProfile
{
private: 
    int m_Experience;
    int m_TownhallLevel;
    int m_Trophies;
public:
    CProfile(void);
    CProfile(int,int,int);
    void PrintInfo(void);
};
#endif 
Run Code Online (Sandbox Code Playgroud)

一切似乎都在编译好,但在此过程中会发生NullReferenceException *profiles = new CProfile[8];.我是C++的新手,我似乎无法弄清楚如何正确地实例化一个类.任何帮助将不胜感激,谢谢.

Pao*_*o M 5

你的代码做了什么:

int main()
{ 
    CProfile **profiles; // define a pointer to a pointer-to-CProfile
    *profiles  = new CProfile[8]; // you dereference "profiles", but... wait, it was just pointing to anywhere
    profiles[0] = new CProfile(2000,2,4); // you are writing into "*profiles" again...
    profiles[1] = new CProfile(55000,6,50); // and so on
    profiles[2] = new CProfile(758200,5,23);
}
Run Code Online (Sandbox Code Playgroud)

你可能意味着什么:

int main()
{
     CProfile* profiles[8]; // define an array of 8 pointers to CProfile
     // assign pointers to unnamed objects to your array
     profiles[0] = new CProfile(2000,2,4);
     profiles[1] = new CProfile(55000,6,50);
     profiles[2] = new CProfile(758200,5,23);
}
Run Code Online (Sandbox Code Playgroud)

最后,我建议你问自己是否可以使用另一种设计:对于你的分配来说,CProfiles对象是否是动态分配的new

例如,您可以使用std::vectorstd::array保存您的个人资料.这就是你可能真正想到的:

int main()
{
    // profiles1 is an array of profiles built without any dynamic allocation
    CProfile profiles1[] = { CProfile(2000,2,4), CProfile(55000,6,50), CProfile(758200,5,23)};

    // profiles2 is a vector of CProfile; 
    // the memory holding your objects is dynamically allocated, but your object aren't
    std::vector<CProfile> profiles2; // profiles is a container of CProfile
    profiles.emplace_back(2000,2,4); // add a CProfile(2000,2,4) at the end of my container
    profiles.emplace_back(55000,6,50); // add a CProfile(55000,6,50) at the end of my container
    profiles.emplace_back(758200,5,23);
}
Run Code Online (Sandbox Code Playgroud)