好吧,伙计们,我失去了它。我花了很多时间,但无法找到线索。 我的测试程序如下:
#include <iostream>
#include <exception>
class SyntaxErrorException : public std::exception
{
public:
const char* what() const throw()
{
return ("SyntaxErrorException thrown");
}
};
int main(void)
{
SyntaxErrorException s;
std::exception& e1 = s;
std::exception& e2 = e1;
try
{
throw (s);
}
catch(const std::exception& e)
{
std::cerr << "Error: " << e.what() << '\n';
}
try
{
throw (e1);
}
catch(std::exception& e)
{
std::cerr << "Error: " << e.what() << '\n';
}
try
{
throw (e2);
}
catch(const std::exception& e)
{
std::cerr << "Error: " << e.what() << '\n';
}
return (0);
}
其输出是:
Error: SyntaxErrorException thrown
Error: std::exception
Error: std::exception
我知道的一件事是,在e1和e2两种情况下,这是关于切片问题。但为什么以及如何呢? 有没有人帮助我理解“抛出表达式”行中到底发生了什么,以便我得到一个基本的 std::Exception 抛出?
最终的情况是我想创建一个通用函数,它将 std::string 自定义错误消息和 std::Exception 引用作为参数索引要抛出的自定义异常。
为什么我不能通过引用将自定义异常类的对象传递给将抛出该异常的函数?还有其他办法吗?
谢谢你
使用函数模板有效
#include <iostream>
#include <exception>
class SyntaxErrorException : public std::exception
{
public:
const char* what() const throw()
{
return ("SyntaxErrorException thrown");
}
};
template<typename T>
void throwException(T& e)
{
throw e;
}
int main(void)
{
try
{
SyntaxErrorException s;
throwException(s);
}
catch(const std::exception& e)
{
std::cerr << "Error: " << e.what() << '\n';
}
return 0;
}
结果:
ERROR!
Error: SyntaxErrorException thrown