2015-08-25 7 views
-1

Мой код выглядит следующим образом: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); 
} 

Где 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 

Все, кажется, собираете штраф, но NullReferenceException происходит во время *profiles = new CProfile[8];. Я новичок в C++, и я не могу понять, как правильно создать экземпляр класса. Любая помощь будет оценена, спасибо.

+3

потому что вы разыменования указателя 'profiles' перед инициализацией его - попробуйте [учебник] (http://www.cplusplus.com/doc/tutorial/pointers/) – BeyelerStudios

+1

Зачем выделять? Почему бы не использовать контейнер STL? – Blacktempel

+1

Совет. Какую память указывает указатель 'profiles', прежде чем вы разыщите его во второй строке? –

ответ

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

То, что вы, вероятно, означает:

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::vector или std::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); 
} 
+0

Я, должно быть, смутил себя понятиями указателей. Кажется, мне удалось заставить его работать так. Каковы были бы другие альтернативы при распределении моих индексов с помощью 'new'? –

+0

@JerYango Две альтернативы показаны в последнем фрагменте кода в моем ответе (отредактированном) –

Смежные вопросы