dragonir 2015-06-02 15:20 采纳率: 100%
浏览 2135
已采纳

Dynamic_cast C++类与对象问题 继承和多态问题,求大神修改

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";
}

}

  • 写回答

5条回答 默认 最新

  • 知常曰明 2015-06-02 22:06
    关注
    • 1.后面两个dynamic_cast没有类型,不知道是你没有用代码格式问题还是你漏了。
    • 2.a转a就不要cast了吧
    • 3.判断要从小到大。
    if(c1!=NULL){
        return "son";
    }
    else if(b1!=NULL){
        return "father";
    }
    else /*if(a1!=NULL)*/{
        return "grandpa";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置