gpt4 book ai didi

c++ - 如何自动化类声明?

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:43 26 4
gpt4 key购买 nike

我有一些异常来自 std::exceptionstd::runtime_error。唯一的方法是构造函数 explicit MyExceptionX(const char *text = "") : std::exception(text) {}。有没有办法在不使用宏的情况下简化此代码?

class MyException1: public std::exception
{
public:
explicit MyException1(const char *text = "") : std::exception(text) {}
};

class MyException2: public std::exception
{
public:
explicit MyException2(const char *text = "") : std::exception(text) {}
};

class MyException3: public std::exception
{
public:
explicit MyException3(const char *text = "") : std::exception(text) {}
};

//...

最佳答案

当一切都是公开的时候就没有必要使用 class 了。您可以改用 struct。此外,您可以继承构造函数:

struct MyException1: std::exception
{
using std::exception::exception;
};

struct MyException2: std::exception
{
using std::exception::exception;
};

struct MyException3: std::exception
{
using std::exception::exception;
};

此外,如果您真的只需要不同的类型,您可以这样做:

template <int>
struct MyException : std::exception
{
using std::exception::exception;
};


using MyException1 = MyException<1>;
using MyException2 = MyException<2>;
using MyException3 = MyException<3>;

如果您想要更具描述性的名称,您可以使用 enum 而不是 int

关于c++ - 如何自动化类声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34982297/

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