zoukankan      html  css  js  c++  java
  • 基于C++的多态性动态判断函数

    这里先有一个问题:

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

    其中,Triangle和Rectangle均继承于Shape类。

    此问题的主函数已规定如下:

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

    分析:首先,问题要求的即类似与Java和C#中的反射机制,这里我们考虑使用dynamic_cast函数,关于用法,我们先看一段函数:

    //A is B's father
    void my_function(A* my_a)
    {
        B* my_b = dynamic_cast<B*>(my_a);
    
        if (my_b != nullptr)
            my_b->methodSpecificToB();
        else
            std::cerr << "  Object is not B type" << std::endl;
    }
    

    只要对对象指针是否是nullptr即可判断该对象运行是是哪个类的对象,全部代码如下:

    #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类型转换操作符完成该函数计算b的顶点数目,若b指向Shape类型,返回值为0;若b指向Triangle类型,返回值为3;若b指向Rectangle类型,返回值为4。*/
    int getVertexCount(Shape * b){
    	Triangle* my_triangle = dynamic_cast<Triangle*>(b);
    	if (my_triangle != nullptr)
    	{
    		//说明是Triangle
    		return 3;
    	}
    	Rectangle* my_Rectangle = dynamic_cast<Rectangle*>(b);
    	if (my_Rectangle != nullptr)
    	{
    		//说明是Rectangle
    		return 4;
    	}
    	return 0;
    }
    
    int main() {
    	Shape s;
    	cout << getVertexCount(&s) << endl;
    	Triangle t;
    	cout << getVertexCount(&t) << endl;
    	Rectangle r;
    	cout << getVertexCount(&r) << endl;
    }
    
  • 相关阅读:
    07.swoole学习笔记--tcp客户端
    06.swoole学习笔记--异步tcp服务器
    04.swoole学习笔记--webSocket服务器
    bzoj 4516: [Sdoi2016]生成魔咒
    bzoj 3238: [Ahoi2013]差异
    bzoj 4566: [Haoi2016]找相同字符
    bzoj 4199: [Noi2015]品酒大会
    后缀数组之hihocoder 重复旋律1-4
    二分查找
    内置函数--sorted,filter,map
  • 原文地址:https://www.cnblogs.com/AvalonRookie/p/7134383.html
Copyright © 2011-2022 走看看