Dynamic_cast
Total: 65 Accepted: 22
Time Limit: 1sec Memory Limit:256MB
Description
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.
以下是我的代码,请问哪里错了,求大神修改 要用 dynamic_cast 做
string verify(A a){
A*p =& a;
A*a1=dynamic_cast<A>(p);
B*b1=dynamic_cast(p);
C*c1=dynamic_cast(p);
if(a1!=NULL){
return "grandpa";
}
if(b1!=NULL){
return "father";
}
if(c1!=NULL){
return "son";
}
}
if(c1!=NULL){
return "son";
}
else if(b1!=NULL){
return "father";
}
else /*if(a1!=NULL)*/{
return "grandpa";
}
你的基类指针要指向子类,然后再用dynamic cast。这才是转换。
之前没有看清楚题目
现在手上没有编译器
参考下这个
http://blog.csdn.net/gogogo/article/details/7073981
和你的类似
string verify(A* pa){
B* pb=dynamic_cast(pa);
C* pc=dynamic_cast(pa);
if(pc != NULL)
return "son";
if(pb != NULL)
return "father";
if(pa != NULL)
return "grandpa";
return NULL;
}
题目是 verify(A*), 然后就是p是A*, 第一个dynamic_cast〈A〉应该是A*把, 然后后面的判断,跟catch类似,最抽象的在最后,不然恒是第一个