Class 数组引用出现 NullReferenceException

NullReferenceException on Class array reference

我的代码如下:

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

其中 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 

似乎编译一切正常,但在 *profiles = new CProfile[8]; 期间出现 NullReferenceException。我是 C++ 的新手,我似乎无法弄清楚如何正确实例化 class。如有任何帮助,我们将不胜感激。

您的代码的作用:

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

你的意思可能是:

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

最后,我建议问问自己是否可以采用另一种设计: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);
}