CHRISTOPHE123
dragonir
2015-06-02 10:49
采纳率: 66.7%
浏览 1.7k

C++一道关于继承的题目,求大神解答,感激不尽

  1. 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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

6条回答 默认 最新

  • caozhy
    已采纳
     #include <iostream>
    #include <string>
    using namespace std;
    
    class A {
    public:
    virtual ~A() {};
    public: virtual string gettype()
    {
        return "grandpa";
    }
    public: static string verify(A * a)
    {
        return a->gettype();
    }
    };
    
    class B: public A 
    {
    public: virtual string gettype()
    {
        return "father";
    }
    };
    
    class C: public B
    {
    public: virtual string gettype()
    {
        return "son";
    }
    };
    
    int main(int argc, char* argv[])
    {
        A a;
        B b;
        C c;
        cout << A::verify(&a) << endl;
        cout << A::verify(&b) << endl;
        cout << A::verify(&c) << endl;
        return 0;
    }
    
    
    点赞 评论
  • caozhy

    grandpa
    father
    son
    Press any key to continue

    点赞 评论
  • houoyufeng
    meetofly 2015-06-02 11:50

    caozhy的答案是正确的

    点赞 评论
  • frank_20080215
    frank_20080215 2015-06-02 13:42

    子类的构造函数需要调用父类的构造函数

    点赞 评论
  • feitianxiaozi
    feitianxiaozi 2015-06-03 03:28

    题本身没难度。。请认真审题

    点赞 评论
  • LogicTeamLeader
    LogicTeamLeader 2015-06-03 07:59

    注意看题目:只写一个函数,不能包括以上的类,也不能包括main函数

    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;
    }
    
    
    点赞 评论

相关推荐