小编Nik*_*lic的帖子

尝试例外和继承

为什么结果是“B”,我认为它应该命中第一个继承类(“A”)?当我使用不从 A 类继承任何内容的 B 类运行它时,它会遇到第一个 catch 块,但我不知道下面的代码中出现这样的行为的原因:

#include <iostream>
#include <exception>

using namespace std;

class A {};

class B : public A{};

class C : public A, public B {};

int main() {
    try {
        throw C();
    }
    catch (A a) {
        cout << "A" << endl;
    }
    catch (B b) {
        cout << "B" << endl;
    }
    catch (C c) {
        cout << "C" << endl;
    }
}   
Run Code Online (Sandbox Code Playgroud)

c++ inheritance try-catch multiple-inheritance

7
推荐指数
1
解决办法
120
查看次数