我对c ++还是比较陌生,需要帮助来了解以下程序的行为。 有人可以帮我理解为什么ptr为null时对funOne的调用有效吗?为什么在funTwo调用中它不起作用?在以下程序中:
IdeOne链接:https://ideone.com/PARm89
#include <iostream>
using namespace std;
class Base
{
public:
virtual ~Base() {}
};
class Derived: public Base
{
int i;
public:
void funOne()
{
cout << "inside funOne()" << endl ;
}
void funTwo()
{
cout << "inside funTwo()" << i << endl ;
}
};
int main()
{
Base* bptr = new Base;
Derived* dptr = dynamic_cast<Derived*>(bptr);
cout << dptr << endl;
cout << bptr << endl;
dptr->funOne(); // why this works?
// dptr->funTwo(); // -> why this does NOT work? it throws exception
int temp;
cin >> temp;
return 0;
}