c++中所有内容的基类

Base class of everything in c++

本文关键字:基类 c++      更新时间:2023-10-16

在Java中,Object类是所有类的基类。C++中也有这样的类吗?

我提出这个问题的动机是:

try
{
    if (something) throw int(a);
    if (something) throw char(b);
    if (something) throw float(c);
}
catch(...)
{
    handle
}

除此之外,还有其他方法可以使用单个catch块来处理所有这些异常吗?

C++中没有通用基类。

异常类通常应该从std::exception派生,以便可以使用catch(const std::exception&)

catch(...)捕获任何异常对象类型(包括基元类型)。可以使用throw;:在catch块内重新抛出

try
{
    if (something) throw int(a);
    if (something) throw char(b);
    if (something) throw float(c);
}
catch(...)
{
    if(stillFailed) throw; // throws the same exception again
}

也可以使用std::current_exception()catch(...)块内获取表示抛出对象(未知类型)的std::exception_ptr对象。然后可以将它与其他std::exception_ptr对象进行相等性比较,或者使用std::rethrow_exception()从另一个函数中重新派生。看见http://en.cppreference.com/w/cpp/header/exception。无法直接访问异常对象,因为其类型未知。

这种情况下最通用的类型是std::string(毕竟,即使是最复杂的程序也只是字符数组)。

将对象编码为文本形式,并在处理端解析/解释它。

template<class T>
std::string toString(const T& x);
try
{
    if (something) throw toString(int(a));
    if (something) throw toString(char(b));
    if (something) throw toString(float(c));
}
catch(const std::string& ex)
{
    decode and handle
}

然而,如果你愿意采用这种方法,那么C++不是进行编程的合适语言——最好改用面向文本或动态语言。

不,有任何其他方法可以单独使用单个catch块来处理所有这些异常。

需要不同的catch块来处理不同的数据类型throw。喜欢对于int捕获(int m)

对于char(字符m)

等等。