程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> 繼承與多態-C++一道關於繼承的題目,求大神解答,感激不盡

繼承與多態-C++一道關於繼承的題目,求大神解答,感激不盡

編輯:編程綜合問答
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.

最佳回答:


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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved