纯虚函数C ++的不同参数

时间:2019-12-21 19:49:22

标签: c++ inheritance virtual-functions

我正在从事有关纯虚函数的任务。我有两个不同的类,希望使用纯虚函数。虚函数用于计算面积,每个类别(即正方形,三角形)使用不同的参数来计算面积。如何使两个getArea函数与纯虚函数一起工作?

#include <iostream>
#include <cmath>

using namespace std;

class Point{
    public:
    double x, y;
    Point(double a = 0, double b = 0){x = a; y = b;}
    Point operator + (Point const &obj){
        Point p;
        p.x = x + obj.x;
        p.y = y + obj.y;
        return p;
    }
     Point operator - (Point const &obj){
        Point p;
        p.x = x - obj.x;
        p.y = y - obj.y;
        return p;
    }
    friend ostream& operator<<(ostream& os, const Point& pt);

};

class Shape{
    public:
    virtual double getArea(Point a, Point b, Point c, Point d) = 0 ; // this is where i have a problem
    // need this to be virtual void getArea() = 0; so i can use it for every other class but not sure how
};

class Square: public Shape{
    public:
 // find area from four points

    double length(Point a, Point b){
        double hDis = pow((b.x - a.x),2);
        double vDis = pow((b.y - a.y),2);
        return sqrt(hDis + vDis);
        }
    double area_triangle(Point a, Point b, Point c){
        double A = length(a, b);
        double B = length (b, c);
        double C = length(a, c);
        double S = (length(a, b) + length (b, c) + length(a, c))/2;
        double area = sqrt((S*(S-A)*(S-B)*(S-C)));
        return area;
        }

    double getArea(Point a, Point b, Point c, Point d){ // have to calculate area with the point coordinates
        double area_tri1 = area_triangle(a, b, c);
        double area_tri2 = area_triangle(a, d, c);
        double total_area = area_tri1 + area_tri2;
        return total_area;
    }
};


class Triangle: public Shape{
    public:
double length(Point a, Point b){
        double hDis = pow((b.x - a.x),2);
        double vDis = pow((b.y - a.y),2);
        return sqrt(hDis + vDis);
        }
    double getArea(Point a, Point b, Point c){
        double A = length(a, b);
        double B = length (b, c);
        double C = length(a, c);
        double S = (length(a, b) + length (b, c) + length(a, c))/2;
        double air = sqrt((S*(S-A)*(S-B)*(S-C)));
        return air;
        }
};

ostream& operator<<(ostream& os, const Point& pt)
{
    os << pt.x << ", " << pt.y <<endl;
    return os;
}


int main(){

    Point p1(5,-5), p2(-10,7), p3(4, 23), p4(-6, 12);

    Square s;
    cout << s.getArea(p1, p2, p3, p4);


    //! Triangle t;
    //! cout << t.getArea(p1, p2,p3);

    // this gives me an error because the abstract function want
    // (Point a, Point b, Point c, Point d)
    // how do i make this work?
}

1 个答案:

答案 0 :(得分:4)

您对课程的设计有些奇怪。

他们应该具有定义其范围的数据成员(“成员变量”)(该特定类型需要的Point个)。

然后无需将任何参数传递到getArea()中:每个类中此函数的实现将使用成员变量!

然后然后,您将不再遇到问题,因为所有getArea()函数将具有相同数量的参数:无。

如果将内容移出函数参数并移入成员变量,以使您的类实际上包含某些 state ,您应该发现设计的其余部分也就此改变而成立。 / p>