2017-12-06 5 views
0

내 모노 폴리 게임에서 Field 유형의 배열을 포함하는 Property : public FieldBoard 클래스 파생 클래스 Field을 기본 클래스로 사용합니다.클래스 디자인 및 상속 문제

class Field { 
protected: 
    int m_position; 
public: 
    Field() { } 
    Field(int p_position) : m_position(p_position) { } 
    virtual void showProperty() const { std::cout << "Actuall output"; }; 
}; 

다음 클래스는 property.cpp에 필드

class Property : public Field { 
    float m_price; 
public: 
    Property(int, float); 
    void showProperty() const; 
}; 

에서 파생 속성입니다

Property::Property(int p_position, float p_price) : Field(p_position), m_price(p_price) { } 

void Property::showProperty() const { 
    std::cout << 
     "Position: " << m_position << "\n" << 
     "Price: " << std::to_string(m_price) << "\n"; 
} 

지금 board.h

constexpr int BOARD_SIZE = 40; 

class Board { 
    std::unique_ptr<Field[]> m_board; 
public: 
    Board(); 
    Field getField(int index) { return m_board[index]; } 
}; 

와 생성자를 볼 수 있습니다

0 주에서
Board::Board() { 
    m_board = std::make_unique<Field[]>(BOARD_SIZE); 
    Property test(1, 100); 
    m_board[0] = test; 
} 

내가이

int main() {  
    Board newBoard; 
    newBoard.getField(0).showProperty(); 
} 

같은 것을 만들고 난 Property::showProperty() 전화를 기대하지만 Field::showProperty()를 호출합니다. 파생 클래스 함수를 사용하는 이유는 무엇입니까?

답변

0

포인터 m_boardField 개체 배열의 첫 번째 요소에 대한 포인터이기 때문에.

즉, m_board[0] = test슬라이스Property 개체를 지정합니다.

포인터 ~ Field의 배열이 필요합니다. 예 물론

std::array<Field*, BOARD_SIZE> m_board; 

를 들어, 배열의 포인터가 실제로 어딘가에 유효 지적하기 위해 기억

m_board[0] = new Property(1, 100); 

또한 물론 당신은 정확하기 getField 함수 반환 유형을 수정해야합니다.