【发布时间】: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