2015-02-03 2 views
0

나는 모든 값과 함수를 가지는 포인터의 배열을 가지고 있습니다. 함수가 실행될 때 값을 찾을 수없는 것처럼 보입니다.함수의 포인터의 배열의 배열

프로그램을 중단시키는 코드는 거의 맨 아래에 있습니다.

내 클래스의 .H 파일 :

#ifndef DICE_H 
#define DICE_H 
class Dice 
{ 
    public: 
     int value; 
     int nrOfFaces; 
     Dice(); 
     void toss(); 
}; 
#endif 

그리고 내 클래스에 대한 내 .cpp 파일 :

#include "Dice.h" 
#include <cstdlib> 
using namespace std; 

Dice::Dice() 
{ 
    nrOfFaces = 6; 
    value = 0; 
} 
//this function gives the dice a new random value 
void Dice::toss() 
{ 
    value = rand() % nrOfFaces + 1; 
} 

main() 함수 :

int main(){ 
    srand(static_cast<unsigned>(time(NULL))); 

    Playboard* board = new Playboard(); 
    Dice** dice = new Dice*[5]; 
    int round = 0; 

    while (1){ 
     system("CLS"); 
     board->PrintBoard(); 

     cout << endl; 

     cout << endl << "Press Enter to roll the dices" << endl; 
     getchar(); 

     for (int i = 0; i < 5; i++) 
     { 
      dice[i]->toss(); //ERROR 
      cout << dice[i]->value << AddSpaces(2); 
     } 
    return 0; 
} 
+0

당신이지고있는 오류 출력은 무엇입니까? – DeadChex

답변

1

dice[i]가있다 포인터 유형. 그리고 당신은 그것에 유효한 포인터를 할당하지 않습니다.

변경 :

for (int i = 0; i < 5; i++) 
    { 
     dice[i]->toss(); //ERROR 
     cout << dice[i]->value << AddSpaces(2); 
    } 

사람 :

for (int i = 0; i < 5; i++) 
    { 
     dice[i] = new Dice(); // Assign a VALID POINTER to dice[i] 
     dice[i]->toss(); //NO ERROR 
     cout << dice[i]->value << AddSpaces(2); 
    } 
+0

처음부터 그랬지만 다음과 같이 수정했습니다. "포인터를 가리키는 5 개의 포인터 배열을 만들어야했습니다. 당신이 한 일은 5 개의 주사위 개체 배열을 가리키는 포인터를 만드는 것입니다. 차이점을 알고 싶습니다. " – Olof

+0

@Olof 그럼 내 생각은 틀렸다. 내 편집을 참조하십시오. –

2

당신은 할당 다섯 포인터의 배열,하지만 포인터를 가리 키도록 실제로 메모리를 할당하지 마십시오. undefined behavior 참조 (초기화되지 않은) 포인터. 초기화되지 않은 메모리의 값은 이며, 불확실한 값은입니다.

std::array<Dice, 5> dice; 

및 일반 배열로 사용이 경우

전혀 포인터 또는 동적 할당을 사용할 필요없다 단지 std::array를 사용

dice[i].toss(); 
+1

특정 이상한 요구 사항 (질문에 언급되지 않은)이있는 클래스 할당처럼 보입니다 –