zoukankan      html  css  js  c++  java
  • C8-3 三角形还是长方形? (100/100 分数)

    题目描述

    在多态概念中,基类的指针既可以指向基类的对象,又可以指向派生类的对象。我们可以使用dynamic_cast类型转换操作符来判断当前指针(必须是多态类型)是否能够转换成为某个目的类型的指针。

    同学们先查找dynamic_cast的使用说明(如http://en.wikipedia.org/wiki/Run-time_type_information#dynamic_cast),然后使用该类型转换操作符完成下面程序(该题无输入)。

    函数int getVertexCount(Shape * b)计算b的顶点数目,若b指向Shape类型,返回值为0;若b指向Triangle类型,返回值为3;若b指向Rectangle类型,返回值为4。

    #include <cstdio>
    #include <cstring>
    #include <iostream>
    using namespace std;

    class Shape{
    public:
    Shape() {}
    virtual ~Shape() {}
    };

    class Triangle: public Shape{
    public:
    Triangle() {}
    ~Triangle() {}
    };

    class Rectangle: public Shape {
    public:
    Rectangle() {}
    ~Rectangle() {}
    };

    /*用dynamic_cast类型转换操作符完成该函数*/
    int getVertexCount(Shape * b){
    }

    int main() {
    Shape s;
    cout << getVertexCount(&s) << endl;
    Triangle t;
    cout << getVertexCount(&t) << endl;
    Rectangle r;
    cout << getVertexCount(&r) << endl;
    }



    输入描述


    输出描述


    样例输入


    样例输出

    #include <cstdio>
    #include <cstring>
    #include <iostream>
    using namespace std;
    
    class Shape{
    public:
        Shape() {}
        virtual ~Shape() {}
    };
    
    class Triangle: public Shape{
    public:
        Triangle() {}
        ~Triangle() {}
    };
    
    class Rectangle: public Shape {
    public:
        Rectangle() {}
        ~Rectangle() {}
    };
    
    /*用dynamic_cast类型转换操作符完成该函数*/
    int getVertexCount(Shape * b){
        Rectangle* rectangle = dynamic_cast<Rectangle*>(b);
        if (rectangle != nullptr)
            return 4;
        Triangle* triangle = dynamic_cast<Triangle*>(b);
        if (triangle != nullptr)
            return 3;
        return 0;
    }
    
    int main() {
        Shape s;
        cout << getVertexCount(&s) << endl;
        Triangle t;
        cout << getVertexCount(&t) << endl;
        Rectangle r;
        cout << getVertexCount(&r) << endl;
    }
    
    
  • 相关阅读:
    如何在 Creator3D 中切换模型贴图,超级简单!
    研究了3天,终于将 Shader 移植到 Cocos Creator 2.2.0 上了!
    Creator3D 守护你的球球—UV动画与天空盒
    一个玩游戏的失足青年,转行做软件开发的挣扎过程
    Cocos Creator 3D 打砖块教程(二) | 子弹发射与摄像机平滑移动
    Cocos Creator 3D 打砖块图文教程(一)
    Creator3D长什么样?看看官方惊艳的DEMO就知道了,附在线体验!
    不要总想着二进制
    关于 JSX
    早教
  • 原文地址:https://www.cnblogs.com/qianxuejin/p/9079393.html
Copyright © 2011-2022 走看看