Three classes A, B and C are shown below:
class A {
public:
virtual ~A() {};
};
class B: public A {};
class C: public B {};
You are to implement a function string verify(A *), such that it returns "grandpa" if the passed-in argument points to a class A object, and "father" for a class B object , "son" for a class C object.
Your submitted source code should include the whole implementation of the function verify, but without any class defined above.
No main() function should be included.
主程序:
#include <iostream>
#include <string>
using namespace std;
class A {
public:
virtual ~A() {};
};
class B: public A {};
class C: public B {};
#include "source"
int main()
{
A a;
B b;
C c;
cout<<verify(&a)<<endl;
cout<<verify(&b)<<endl;
cout<<verify(&c)<<endl;
return 0;
}
答案程序 "source":
string verify(A *p)
{
if (dynamic_cast<C*>(p))
return "son";
else if (dynamic_cast<B*>(p))
return "father";
else
return "grandpa";
}