gpt4 book ai didi

c++ - Visual Studio 2017 警告说异常被基类捕获,但事实并非如此

转载 作者:行者123 更新时间:2023-12-02 14:23:44 24 4
gpt4 key购买 nike

我开始学习 C++ 中的异常,并开始在 VS17 中处理它们。我发现,如果派生类是公开派生的,则基类的捕获将捕获派生类的对象。 VS 仍然给了我一个警告: 1> warning C4286: 'B': is catched by base class ('A') 这让我很困惑,因为程序似乎工作正常。对此有解释还是我遗漏了一些重要的东西?

#include <iostream>
#include <string>
using namespace std;


class A {
protected:
int d;
public:
A(int h = 3) :d(h) { cout << "Constructor A" << endl; }
friend ostream& operator<<(ostream& os, const A& a) {
os << "Caught A " << endl;
return os;
}
};
//Private inheritance
class B : A {
int e;
public:
B(int i = 8) : e(i) { cout << "Constructor B " << e << d << endl; }
friend ostream& operator<<(ostream& os, const B& b) {
os << "Caught B" << endl;
return os;
}
};


double find_root(int f) {
if (f <= 0) throw B(7);
return sqrt(f);
}

int main() {

try {

try {
cout << find_root(-1) << endl;
}

catch (B b) { cout << "Exception in inside Block" << endl; throw; }

}

catch (int) {
cout << "Number smaller than 0" << endl;
}

catch (A a) {
cout << a;
}

catch (B b) {
cout << b;
}

int g; cin >> g;
}

最佳答案

这很可能是 Visual Studio 2017 的问题。我已经使用 gcc 9.x 编译了您的代码,看来 gcc 可以根据公共(public)或私有(private)继承为您提供正确的警告。网上查码here

关于c++ - Visual Studio 2017 警告说异常被基类捕获,但事实并非如此,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59529653/

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