c++编程。(1)定义父类point,包含x和y两个坐标属性

2024年11月29日 20:38
有3个网友回答
网友(1):

#include 

using namespace std;

class point{
public:
    point( double x = 0.0, double y = 0.0 ){
        m_x = x;
        m_y = y;
    }

    void show(){
        cout << "x = " << m_x << "," << "y = " << m_y << endl;
    }

private:
    double m_x;
    double m_y;
};

class circle : public point{
public:
    circle(  double r, double x = 0.0, double y = 0.0)
        : point( x, y){
        m_r = r;
    }

    void show(){
        point::show();
        cout << "r = " << m_r << endl;
    }

private:
    double m_r;
};

int main()
{
    circle dc(100,20,30);
    dc.show();

    return 0;
}

网友(2):

Point类public class Point{private float x;private float y;public Point(float x,float y){this.x = x;this.y = y;}public float getX() {return x;}public void setX(float x) {this.x = x;}public float getY() {return y;}public void setY(float y) {this.y = y;}public float distanceToOrigin(){return (float) Math.sqrt(Math.pow(this.x, 2)+Math.pow(this.y, 2));}public float distanceToOther(int x, int y){return (float) Math.sqrt(Math.pow(this.x-x, 2)+Math.pow(this.y-y, 2));}public float distanceToOther(Point point){return (float) Math.sqrt(Math.pow(this.x-point.x, 2)+Math.pow(this.y-point.y, 2));}}测试类public class TestPoint{public static void main(String[] args) {Point p1 = new Point(3, 5);Point p2 = new Point(7, 8);System.out.println(p1.distanceToOrigin());System.out.println(p2.distanceToOrigin());System.out.println(p1.distanceToOther(20,30));System.out.println(p2.distanceToOther(20,30));System.out.println(p1.distanceToOther(p2));}}

网友(3):

public class Point {
private T x;
private T y;

public Point(T x, T y) {
this.x = x;
this.y = y;
}

public T getX() {
return x;
}

public void setX(T x) {
this.x = x;
}

public T getY() {
return y;
}

public void setY(T y) {
this.y = y;
}

public void outPut(Point p){
System.out.println("点的x坐标为:"+p.getX());
System.out.println("点的y坐标为:"+p.getY());
}

public static void main(String[] args) {
Point p=new Point(1,2);
p.outPut(p);

Point d=new Point(1.0,2.0);
d.outPut(d);

Point f=new Point(1.0f,2.0f);
f.outPut(f);

}

}