提问人:evanparial 提问时间:9/5/2022 更新时间:9/5/2022 访问量:89
如何让 setter 函数使用 c++ 演示 List 中的异常处理?
How do I make a setter function demonstrate exception handling in a List using c++?
问:
我正在尝试创建一个 setter 函数,您可以在其中替换列表中某个位置的歌曲,同时仍然演示异常处理。为此,我专注于 setEntry()。
这是我的 List 类:
class List
{
private:
static const int CHUNK_SIZE=100;
ItemType *list;
int numItems;
int maxItems;
public:
// default constructor and destructor
List()
{
numItems = 0;
maxItems = CHUNK_SIZE;
list = new ItemType[CHUNK_SIZE];
}
~List()
{
delete[] list;
}
// list member functions
bool isEmpty() const
{
return numItems==0;
}
int getLength() const
{
return numItems;
}
bool insert(int pos, const ItemType& item);
bool remove(int pos);
// clear the list
// clear can simply set numItems to zero. The array list may still contain
// items already inserted into the list, but since numItems is zero, there
// isn't any way to get at them using getEntry() or setEntry()
void clear()
{
numItems = 0;
}
// return entry at postion pos
// throw invalid_argument if pos<1 or pos>getLength()
ItemType getEntry(int pos) const;
// set entry at postion pos to item
// throw invalid_argument if pos<1 or pos>getLength()
// changes whatever is inside the position to that item. swap.
void setEntry(int pos, const ItemType& item);
};
我的老师希望 setEntry 将位置 (pos) 设置为歌曲 (item),invalid_argument并在 pos < 1 ||pos > getLength()。当我尝试在我的 main 方法中设置 setEntry() 时,它只是抛出异常。在我看来,(list[pos] = item)似乎是对的,因为添加时不必将所有数据向右移动,只需替换它即可。这是怎么回事?如何在运行代码时仍测试异常?
下面是 setEntry():
template<class ItemType>
void List<ItemType>::setEntry(int pos, const ItemType& item)
{
list[pos] = item;
if (pos < 1 || pos > getLength())
{
throw invalid_argument("ERROR: setEntry() using invalid position");
}
}
这是我的主要方法:
int main()
{
List<string> songs;
char goAgain = 'y';
int trackNumber;
string trackName;
// Insert some songs into our list
songs.setEntry(2, "Bohemian Rhaspody");
songs.insert(1, "Bohemian Rhaspody");
songs.insert(2, "The Highway Song");
songs.insert(3, "In the Loop");
songs.insert(4, "Lovesong");
songs.insert(5, "Blow The Whistle");
songs.remove(1);
cout << "Welcome! There are " << songs.getLength() << " tracks.\n";
while (goAgain!='n')
{
trackNumber = getTrack();
try
{
trackName = songs.getEntry(trackNumber);
}
catch (invalid_argument arg)
{
cout << arg.what() << endl;
trackName = "No Track";
}
cout << "Your track name is " << trackName << endl;
cout << "Go again? (y/n) ";
cin >> goAgain;
}
cout << "you're ready to rock!\n";
return 0;
}
以及它输出的错误:
libc++abi: terminating with uncaught exception of type std::invalid_argument: ERROR: setEntry() using invalid position
[1] 48422 abort
答: 暂无答案
评论
setEntry
pos
setEntry
pos
list[]
是从向上索引的,而不是 .另外,在尝试插入项目之前,您不应该检查错误吗?0
1
0
length-1
pos >= getLength()
pos > getLength()