[英]Pure virtual functions and unused arguments in child functions in C++
[英]Different arguments to pure virtual functions c++
我正在做一個關於純虛函數的作業。 我有兩個不同的類,我希望使用純虛函數。 虛函數用於計算面積,每個類即(正方形、三角形)使用不同的參數來計算面積。 我怎樣才能讓兩個 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?
}
你設計的課程有點奇怪。
它們應該具有定義其范圍的數據成員(“成員變量”)(該特定類型所需的Point
數量)。
那么就不需要將任何參數傳遞給getArea()
:每個類中該函數的實現都將使用成員變量!
然后你就不會再有問題了,因為所有的getArea()
函數都將有相同數量的參數:無。
如果你把東西從函數參數中移到成員變量中,這樣你的類實際上包含一些state ,你應該會發現你的設計的其余部分圍繞着這個變化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.