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

问题描述 投票:0回答:1

我正在从事有关纯虚函数的任务。我有两个不同的类,希望使用纯虚函数。虚函数用于计算面积,每个类别(即正方形,三角形)使用不同的参数来计算面积。如何使两个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?
}
c++ inheritance virtual-functions
1个回答
2
投票

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

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

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

然后然后

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

如果将内容移出函数参数,并移入成员变量,以使您的类实际上包含某些state

,则应该发现其余的设计都围绕着该更改。
© www.soinside.com 2019 - 2024. All rights reserved.