我有这段代码:
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
为什么会出现此错误?
答案 0 :(得分:0)
致电
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。
答案 1 :(得分:0)
您当前的代码包含很多错误。这里有几个:
Repo
构造函数没有按照您的想法执行。 RepoException
的构造函数应接受const std::string&
或std::string
RepoException
应来自std::exception
RepoException
,但RepoException
没有复制构造函数仔细看看你的代码,我认为你真的想要使用std::set
,它只包含唯一的值。它还经过优化,可以检查集合中是否存在该值:
template<typename T> using Repo = std::set<T>;