pr27001.cpp

来自「《标准C++宝典》源码」· C++ 代码 · 共 65 行

CPP
65
字号
////////////////////////////////////////
// File Name: pr27001.cpp
////////////////////////////////////////
#include <typeinfo>
#include <iostream>

////////////////////////////////////////
// Define the Shape class.
////////////////////////////////////////
class Shape
{
public:
    virtual void foo() {}  // To enable rtti.
};

////////////////////////////////////////
// Declare classes derived from Shape.
////////////////////////////////////////
class Circle    : public Shape { };
class Rectangle : public Shape { };

////////////////////////////////////////
// Process Circle and Rectangle objects.
////////////////////////////////////////
void Process(Shape* sp)
{
    // Downcast Shape* to Circle*.
    Circle* cp = dynamic_cast<Circle*>(sp);
    if (cp != 0)
    {
        std::cout << "Processing a Circle" << std::endl;
        return;
    }

    // Downcast Shape* to Rectangle*.
    Rectangle* rp = dynamic_cast<Rectangle*>(sp);
    if (rp != 0)
    {
        std::cout << "Processing a Rectangle" << std::endl;
        return;
    }

    std::cout << "Unknown Shape, cannot process" << std::endl;
}

////////////////////////////////////////
// The main() function.
////////////////////////////////////////
int main()
{
    // Instantiate and process a Circle.
    Circle circle;
    Process(&circle);

    // Instantiate and process a Rectangle.
    Rectangle rect;
    Process(&rect);

    // Instantiate and process a generic Shape.
    Shape shape;
    Process(&shape);

    return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?