读取访问冲突

时间:2017-12-05 21:11:38

标签: c++ exception access-violation

我试图写大富翁游戏而且我被困了。

首先让我们展示我的类层次结构

class Player {  
    std::vector<Property> m_properties;
public:
    void addProperty(const Property &p_property) { m_properties.push_back(p_property); }
    void showProperties();
    void showPlayer();
}

void Player::showProperties() {
    for (int i = 0; i < m_properties.size(); i++) {
        std::cout << "Property nr " << i << "\n" << m_properties[i].showProperty();
    }
}

void Player::showPlayer() {
    std::cout << "Name: " << m_name << "\n"
              << "Position: " << m_position << "\n"
              << "Cash: " << m_cash << "\n"
              << "In jail?: "; 
                if (m_inJail== true) std::cout << "Yes\n";
                else std::cout << "No\n";
    std::cout << "Properties: \n";
    showProperties();
}

Class Property及其showProperty()函数

std::string Property::showProperty() const {
    std::string s = "Name: " + m_name + "\n"
        + "Group:" + m_group + "\n"
        + "Price:" + std::to_string(m_price) + "\n"
        + "Owner:" + m_pOwner->getName();
    return s; 
}   

这是将属性添加到播放器向量

的方法
void PropertyManager::buyProperty(Property &p_property, Player &p_player) { 
    if (p_property.getOwner() == nullptr) {
        if (p_player.getCash() >= p_property.getPrice()) {
            p_player.addProperty(p_property);
            p_player.takeCash(p_property.getPrice());
            p_property.setOwner(p_player);
        }
        else cout << "Sorry, you don't have enough cash. \n";
    }
    else cout << "Sorry, this property is owned by somebody else. \n";
}

所以你可以看到,Player包含vector,Property有返回字符串的方法,其中包含有关Property对象的基本数据。在PropertyManager类中,我有方法buyProperty,检查它是否可用,然后将所选属性添加到选定的播放器,它工作,播放器丢失现金,propety获得所有者。但现在我想展示玩家拥有的所有属性。我的Player::showPlayer()调用了Player::showProperties(),另一方面调用了Property::showProperty() m_properties[i].showProperty()

Finnaly我的主要功能

int main() {
    Field *board[10];
    Property testProperty(PropertyType::BuildingArea, 5, "Test", "Test", 3, 1000, 100, 400, 150);
    Player player("Testplayer", 5000);  
    PropertyManager manager;
    board[0] = &testProperty;   
    manager.buyProperty(testProperty, player);  
    player.showPlayer();    

    std::cin.get();
}

不幸的是它抛出异常

  

抛出未处理的异常:读取访问冲突。   _Right_data是nullptr。

似乎Player::showProperties()导致了这个问题,当我不打电话给这个函数时,程序有效。

0 个答案:

没有答案