C++有关类与对象的问题


# include
using namespace std;

class Point {      //定义类 点
public:
    void dian(float X, float Y);
    float getX();
    float getY();
private:
    float x, y;
};
inline void Point::dian(float X, float Y) {      //点坐标
    x = X;
    y = Y;
}
inline float Point::getX() {      //横坐标
    return x;
}
inline float Point::getY() {      //纵坐标
    return y;
}

class Rectangle {      //定义类 矩形
public:
    Point A, B;
    float area();
    void show();
private:
    float S;
};
inline float Rectangle::area() {      //求面积
    float width, height;
    width = B.getX() - A.getX();      //横坐标增量
    height = B.getY() - A.getY();      //纵坐标增量
    S = width * height;
}
inline void Rectangle::show() {      //显示面积
    cout << "该矩形面积为:" << S << endl;
}

int main() {
    Rectangle M;
    Point A, B;
    float x1, y1, x2, y2;
    cout << "请输入矩形左下角坐标:" << endl;
    cin >> x1 >> y1;
    A.dian(x1, y1);
    cout << "请输入矩阵右上角坐标:" << endl;
    cin >> x2 >> y2;
    B.dian(x2, y2);
    M.show();
    return 0;
}

我先定义了一个Point类,然后在Rectangle类中使用了Point类,结果不知道哪儿错了,输出的面积竟然让我看不懂(悲
希望懂的人帮我看看(玫瑰

img

cout << "该矩形面积为:" << area() << endl;


# include<iostream>
using namespace std;

class Point {      //定义类 点
public:
     Point (int X=0, int Y=0);     //构造函数
    int getX();
    int getY();
    Point(Point& p);      //复制构造函数
private:
    int x, y;
};
Point::Point(int X, int Y) {      //构造函数
    x = X;
    y = Y;
}
inline int Point::getX() {    
    return x;
}
inline int Point::getY() {    
    return y;
}
Point::Point(Point& p) {      //定义复制构造函数
    x = p.x;
    y = p.y;
    cout << "使用了Point的复制构造函数" << endl;
}

class Rectangle {      //定义类 矩形
private:
    Point A;
    Point B;
public:
    Rectangle(Point a, Point b);
    void show();
    Rectangle (Rectangle& r);
private:
    int S;
};
Rectangle::Rectangle (Point a,Point b):A(a),B(b) {      //求面积 构造函数 课本118-119页组合类的构造函数
    int width, height;
    width = A.getX() - B.getX();      
    height = A.getY() - B.getY();     
    S = width * height;
}
inline void Rectangle::show() {      
    cout << "该矩形面积为:" << S<< endl;
}
Rectangle::Rectangle(Rectangle& r) :A(r.A), B(r.B) {
    cout << "使用了复制构造函数Rectangle" << endl;
    S = r.S;
}

int main() {
    int x1, y1, x2, y2;
    cout << "输入左下角坐标x1、y1和右上角坐标x2、y2" << endl;
    cin >> x1 >> y1 >> x2 >> y2;
    Point m(x1, y1), n(x2, y2);
    Rectangle Rectangle(m, n);
     Rectangle.show();
     return 0;
}

换成构造函数,这个运行结果就不会出错,不是很清楚,但总之能成功就是好事,庆祝一下!