【问题标题】:Class design and inheritance issue类设计和继承问题
【发布时间】:2017-12-06 11:16:57
【问题描述】:

所以在我的大富翁游戏中,我有基类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"; };
};

下一个类是从 Field 派生的 Property

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

在property.cpp中

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

及其构造函数

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()。为什么不使用派生类函数?

【问题讨论】:

    标签: c++ polymorphism virtual smart-pointers


    【解决方案1】:

    因为您的指针 m_board 是指向 Field 对象数组的第一个元素的指针。

    这意味着分配m_board[0] = test切片 Property 对象。

    您需要一个指向Field指针 数组。例如

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

    当然,请记住让数组中的指针实际上指向某个有效的地方:

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

    当然您还需要修改getField 函数的返回类型以使其正确。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-06
      • 1970-01-01
      • 2021-10-21
      相关资源
      最近更新 更多