从这里的答案中,我实现了我的类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( 可能是这种情况:
首先,从表达式复制初始化异常对象(这可能会调用右值表达式的移动构造函数,并且复制/移动可能会受到复制省略的影响(
我尝试添加
NotImplementedException(const NotImplementedException&) = default;
NotImplementedException& operator=(const NotImplementedException&) = default;
到我的班级,但这给了我
error C2512: 'BSE::NotImplementedException': no appropriate default constructor available
据我所知,std::logic_error
没有定义默认构造函数。
问:我该如何解决这个问题?
它应该是这样的:
namespace base
{
class NotImplementedException : public std::logic_error
{
public:
NotImplementedException () : std::logic_error{"Function not yet implemented."} {}
};
}
然后
std::string to_string() override
{
throw NotImplementedException();
}
没有说明未实现的内容的异常非常烦人,所以我会这样做:
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 功能在这种情况下很酷,但不是强制性的(并且在大多数编译器上仍然不可用(。
一些演示。