C++ 程序异常处理的输出是什么? #包括 结构泛型异常{ virtual void print(){std::cout
代码:C++ 程序异常处理的输出是什么? #包括 结构泛型异常{ virtual void print(){std::cout,c++,exception,struct,constructor,C++,Exception,Struct,Constructor,代码: #include <iostream> struct GeneralException { virtual void print() { std::cout << "G"; } }; struct SpecialException : public GeneralException { void print() override { std::cout << "S"; } }; void f() { throw SpecialExcept
#include <iostream>
struct GeneralException {
virtual void print() { std::cout << "G"; }
};
struct SpecialException : public GeneralException {
void print() override { std::cout << "S"; }
};
void f() { throw SpecialException(); }
int main() {
try {
f();
}
catch (GeneralException e) {
e.print();
}
}
此默认值构造一个SpecialException
实例并将其抛出。对于SpecialException
,没有注册的特定处理程序,但对于基类,GeneralException
,有一个处理程序是按值执行的,这意味着您的SpecialException
实例将被切片为GeneralException
,结果是打印..G
如果希望/期望打印S
,则必须通过引用捕获该异常,最好是const
,这将需要在两种实现中都执行print
const。结果如下所示:
throw SpecialException();
我想你对接球和投掷的工作方式感到困惑。 让我用一段代码来展示这个
S
while(ch!=“n”){
试一试{
cout输出将为
while(ch != 'n'){
try{
cout<<"Enter some number"'; // Let us suppose we want to enter some int.
cin>>num; // think that you enter char here.Ideally it show exit due to your input.But since we have made this statement in try block. It'll try to look for some handler who can handle such errors.
cout<<"Wanna enter more. Enter y or n -"<<endl;
cin>>ch;
if(!cin){ // since you entered char when int was required. stream will corrupt.
throw runtime_error("Input failed.\n");} // here we are throwing it.We are throwing it to runtime_error. It will search for it and go to that block.
}
catch(runtime_error error){ // This will catch it.
cout<<error.what()
<<"Try again? Enter y or n.\n";
char c; //if you enter y it will go back to take input since it's while loop.
cin>>c;
if(!cin || c=='n'){
break;
}
}
}
简单来说,当您编写throw SpecialException()
时,它只创建SpecialException
的对象,并将其传递给catch块中的GeneralException
的对象
换句话说,如果我把事情放在一起,你可以假设这就是实际发生的事情
G
从这一点可以非常清楚地看出,没有发生多态性,并且e.print();
将打印G
,这是print()
在GeneralException
类中定义的print()
版本
要利用多态性,请按照@WhozCraig answer所述更新您的代码。可能重复的
G
//throw statement
SpecialException s;
//catch statment
GeneralException e = s;
e.print();