#include <iostream>
using namespace std;
class A{
public:
A() {std::cout<<"A() ";}
A(const A& a){cout<<"A(const A&) ";}
~A(){cout<<"~A() ";}
virtual void Foo(){cout<<"A::Foo() ";}
};
class B: public A
{
public:
B(){std::cout<<"B() ";}
B(const B& a){cout<<"B(const B&) ";}
~B(){cout<<"~B() ";}
virtual void Foo() {cout<<"B::Foo() ";}
};
int main()
{
try{
B b;
throw b; //throw like this
}
catch(A ex){
ex.Foo();
}
catch(B ex){
ex.Foo();
}
catch(A * ex){
ex->Foo();
}
catch(B * ex){
ex->Foo();
}
return 0;
}
输出
A()B()A()B(const B&amp;)〜B()~A()A(const A&amp;)A :: Foo()~A()〜B()~A()
#include <iostream>
using namespace std;
class A{
public:
A() {std::cout<<"A() ";}
A(const A& a){cout<<"A(const A&) ";}
~A(){cout<<"~A() ";}
virtual void Foo(){cout<<"A::Foo() ";}
};
class B: public A
{
public:
B(){std::cout<<"B() ";}
B(const B& a){cout<<"B(const B&) ";}
~B(){cout<<"~B() ";}
virtual void Foo() {cout<<"B::Foo() ";}
};
int main()
{
try{
throw B(); //throw it this way
}
catch(A ex){
ex.Foo();
}
catch(B ex){
ex.Foo();
}
catch(A * ex){
ex->Foo();
}
catch(B * ex){
ex->Foo();
}
return 0;
}
输出
A()B()A(const A&amp;)A :: Foo()~A()~B()〜A()
有人可以向我解释一下这个区别吗? 差异是
A()B(const B&amp;)~B()〜A()
为什么要调用B类的复制构造函数?
非常感谢!
答案 0 :(得分:4)
因为在第一个示例中,首先在b
行复制局部变量throw
,然后在catch ( A ex )
行进行切片,而在第二个样本中只复制第二个副本执行。
我想我必须在这里提到throw by value, catch by reference口头禅:)