在答案这里中,我实现了类NotImplementedException
//exceptions.h
namespace base
{
class NotImplementedException : public std::logic_error
{
public:
virtual char const* what() { return "Function not yet implemented."; }
};
}在另一个类中,我想抛出以下异常(相同的命名空间):
std::string to_string() override
{
throw NotImplementedException();
}to_string方法是来自抽象基类的覆盖方法。
namespace BSE {
class BaseObject
{
virtual std::string to_string() = 0;
};
}不幸的是,前面代码的编译显示了这个错误:
error C2280: BSE::NotImplementedException::NotImplementedException(void)': attempting to reference a deleted function`从这里中,我了解到问题与移动构造函数或赋值有关,根据cppreference.com -掷(1),这可能是这样的:
首先,从表达式初始化异常对象(这可能会调用rvalue表达式的移动构造函数,并且复制/移动可能会受到复制省略的影响)。
我试着添加
NotImplementedException(const NotImplementedException&) = default;
NotImplementedException& operator=(const NotImplementedException&) = default;给我的班级,但这给了我
error C2512: 'BSE::NotImplementedException': no appropriate default constructor available据我所知,std::logic_error没有定义默认构造函数。
Q:我该如何解决这个问题?
发布于 2017-03-21 22:33:04
应该是这样的:
namespace base
{
class NotImplementedException : public std::logic_error
{
public:
NotImplementedException () : std::logic_error{"Function not yet implemented."} {}
};
}然后
std::string to_string() override
{
throw NotImplementedException();
}发布于 2022-02-14 09:59:59
没有说明未实现的异常非常烦人,所以我会这样做:
namespace base
{
class NotImplementedException : public std::logic_error
{
public:
using logic_error::logic_error;
NotImplementedException(
const std::source_location location = std::source_location::current())
: logic_error{std::format("{} is not implemented!", location.function_name())}
{}
};
}然后
std::string to_string() override
{
throw NotImplementedException("to_string for object");
// or using source_location:
throw NotImplementedException();
}对于这种情况,C++20特性是很酷的,但并不是必须的(大多数编译器仍然无法使用)。
一些演示。
https://stackoverflow.com/questions/42939299
复制相似问题