非成员函数和抽象类

时间:2019-07-18 22:50:07

标签: visual-c++

因此,目标是创建一个以“矩形”和“三角形”为派生类的抽象“形状”类。通过使用main()中的非成员函数打印矩形和三角形的周长和区域来完成分配。我在如何仅使用一个非成员函数方面遇到麻烦,而不是为每种形状创建打印函数:

void printPerimeter(Triangle triangle);
void printPerimeter(Rectangle rectangle);
//I'm trying not to do this
//what I had in mind, but don't know how to work this problem.
void printPerimeter(Shape shape)
{
    float temp;
    temp = shape.calcPerimeter();
    cout << "Perimeter: " << temp << endl;
}

我知道不能将抽象类传递给函数,那么我该怎么办呢?

1 个答案:

答案 0 :(得分:0)

class Shape
{
private:

public:
    virtual void calcPerimeter()
    {
        cout << "Shape" << endl;
    }
};

class Triangle1 : public Shape
{
public:
    void calcPerimeter()
    {
        cout << "Triangle" << endl;
    }
};

class Rectangle1 : public Shape
{
public:
    void calcPerimeter()
    {
        cout << "Rectangle" << endl;
    }
};

void printPerimeter(Shape* shape)
{
    shape->calcPerimeter();
}

int main()
{
    Shape *triangle = new Triangle1();
    Shape *rectangle = new Rectangle1();

    printPerimeter(triangle);
    printPerimeter(rectangle);
    return 0;
}

请检查这是否有助于您实现目标。礼貌:@Renired Ninja