gpt4 book ai didi

c++ - 当我尝试抛出异常时没有匹配函数错误

转载 作者:太空宇宙 更新时间:2023-11-04 13:49:56 24 4
gpt4 key购买 nike

我有这个代码:

class RepoException
{

public:

RepoException(string& msg)
{
this->msg=msg;
}

string& getMsg()
{
return this->msg;
}

private:

string msg;
};

template<typename T>
class Repo
{

public:

Repo()
{
vector<T> elems;
}

void store(T elem) throw (RepoException)
{
for(int i =0; i<elems.size();i++)
{
if (elems[i]->getId() == elem->getId())
{
throw RepoException("There is a person with same id ");
}

}
elems.push_back(elem);
}

在函数 store 中,当我尝试抛出异常时出现此错误:

  Multiple markers at this line
- candidates are:
- no matching function for call to 'RepoException::RepoException(const

为什么会出现此错误?

最佳答案

通话中

RepoException( "There is a person with same id ")

参数“There is a person with same id”的类型是const char []。这不能用于转换成字符串,但如果你这样写就可以:

RepoException( const string& msg)

一个好的做法是从 std::exception 派生异常,即 std::runtime_error .

关于c++ - 当我尝试抛出异常时没有匹配函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23860561/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com