使用类作为参数的函数

时间:2013-10-05 22:09:53

标签: c++

我遇到了这个功能的问题:

double area( const Point & a, const Point & b, const Point & c ); 

此功能的说明如下:

Area是一个非成员函数,使用其3 Point args进行计算。具体来说,它计算并返回三角形的区域,顶点由3个点表示。

非常感谢任何帮助。谢谢!

# include <string>
# include <iostream>
# include <cmath>
using namespace std;

class Point{
    public:
        Point( double x = 0, double y = 0 );
        double getX() const;
        double getY() const;
        Point & setX( double x );    //  mutator, returning reference to self
        Point & setY( double y );
        const Point & output() const;
        double distance( const Point & other ) const;
    private:
        double myX;
        double myY;
    };
double area( const Point & a, const Point & b, const Point & c );

int main (){


    Point a;
    Point b;
    Point c;

    a.setX (2);
    a.setY (0);
    b.setX (0);     
    b.setY (1);
    c.setX (0);
    c.setY (0);


    system ("pause");

}//main

Point :: Point( double x, double y){
    setX (x);
    setY (y);
}// ctr
 double Point :: getX() const{
    return myX;
}//getX
double Point :: getY() const{
    return myY;
}//getY
Point & Point :: setX( double x ){
    myX = x;
    return *this;
}//setX
Point & Point :: setY( double y ){
    myY = y;
    return *this;
}//setY
const Point & Point :: output() const{
    cout << "(" << myX << "," << myY << ")" << endl;
    return *this;
}//output
double Point :: distance( const Point & other ) const{
    double d;
    d = sqrt(pow(other.myX-myX,2)+pow(other.myY-myY,2));
    return d;
}//distance

double area( const Point & a, const Point & b, const Point & c ){

    Point area;

    double length1, length2, length3;
    double s, area1;
    length1 = sqrt(pow(a.getX-b.getX,2)+pow(a.getY-b.getY,2));
    length2 = sqrt(pow(b.getX-c.getX,2)+pow(b.getY-c.getY,2));
    length3 = sqrt(pow(a.getX-c.getX,2)+pow(a.getY-c.getY,2));

    s = (length1+length2+length3)/2;


    area1 = sqrt(s*(s-length1)(s-length2)(s-length3));

return area1;

}//area

1 个答案:

答案 0 :(得分:0)

我认为您的代码存在问题,因为在()函数中调用Point的方法时省略了 area ,例如

length1 = sqrt(pow(a.getX-b.getX,2)+pow(a.getY-b.getY,2));
length2 = sqrt(pow(b.getX-c.getX,2)+pow(b.getY-c.getY,2));
length3 = sqrt(pow(a.getX-c.getX,2)+pow(a.getY-c.getY,2));

您应该使用a.getX()b.getX()