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;
    }
    
  • 相关阅读:
    ThreadLocal的原理和使用场景
    sleep wait yield join方法的区别
    GC如何判断对象可以被回收
    双亲委派
    ConcurrentHashMap原理,jdk7和jdk8版本
    hashCode和equals
    接口和抽象类区别
    为什么局部内部类和匿名内部类只能访问局部final变量
    【GAN】基础GAN代码解析
    TF相关codna常用命令整理
  • 原文地址:https://www.cnblogs.com/AvalonRookie/p/7134383.html
Copyright © 2011-2022 走看看