【问题标题】:Access violation reading location when using recursion?使用递归时访问冲突读取位置?
【发布时间】:2020-05-03 12:29:17
【问题描述】:

下面的代码用作交易功能的一部分,其中显示了属性列表以及他们想要交易的属性中使用的类型。

当用户输入不存在的属性(运行 catch 块)然后输入有效属性时,propertyName 变量上会出现“访问冲突读取位置错误”。

我不明白为什么会抛出这个错误,我猜这是我在 catch 块中使用 getline 或递归我无法解决的问题。

玩家交易功能

void player::trade(player &tradePlayer){
    ***

    //code extract
    cout << "What properties would you like from " << tradePlayer.getPlayerName() << " ? (Enter done when finished selecting)" << endl;
    string propertyName;
    vector<properties> theirProperties; 
    int theirCash;
    ws(cin);
    getline(cin, propertyName); //gets property name
    while (propertyName != "done") {
        theirProperties.push_back(tradePlayer.getOwnedProperty(propertyName));
        getline(cin, propertyName); **Access violation appears here**
    }

    ***

玩家类 - getOwnedProperty()

class player
{
public:

***
    //code extract
    properties &getOwnedProperty(string name) {
        try {
            for (int i = 0; i < ownedProperties.size(); i++) {
                if (ownedProperties.at(i).getProperty() == name) {
                    return ownedProperties.at(i);
                }
            }
            throw exception();
        }
        catch (exception){
            cout << "Property name not recognised! Try again." << endl;
            ws(cin);
            getline(cin, name);
            getOwnedProperty(name);
        }

    }

***

}

【问题讨论】:

    标签: c++ try-catch access-violation


    【解决方案1】:

    您的异常被抛出,因为您的循环在 getOwnedProperty() 函数中找不到与其 if() 语句匹配的任何内容。用 == 操作符比较字符串值是错误的,所以你应该使用 string::compare() 方法。在此处了解如何使用它:https://www.geeksforgeeks.org/stdstringcompare-in-c/

    【讨论】:

    • 如果 if() 语句未能在ownedProperty 函数中找到匹配项,则会引发异常,然后运行包含递归的 catch 块。这一直持续到用户输入与 if() 语句匹配的属性。使用递归时我的逻辑是否遗漏了什么?
    • 一般来说,不鼓励递归,除非在简单性和代码清晰性方面真正有用。其次,异常处理在性能方面也很昂贵,因此您应该真正使用它来处理程序中的异常错误状态。因此,我真的建议您通过避免异常和递归来重组您的代码,并在这种特殊情况下支持 do-while 循环。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2016-05-28
    相关资源
    最近更新 更多