在不改变现有main.cpp的情况下,写一个shape.h和一个shape.cpp来计算两个长方形的大小同时用is_larger比较大小,同时重载运算符 >,下面是main.cpp
#include<iostream>
#include"shape.h"
using namespace std;
int main()
{
// construct a point at position (1,1)
// constuctor of class "Point" is called
Point p(1,1);
// construct two rectangles using different parameters
Rectangle r1; //r1 is initialized of size 1X1 at the origin
Rectangle r2(p,0.3,2.9);
// move rectangle r1
// shift the rectangle horizontally by 0.2
// shift the rectangle vertically by -1.3
r1.move(0.2,-1.3);
// compute the areas using member function .area()
cout << r1.area() << endl;
cout << r2.area() << endl;
// compare whether r1 has a larger area than r2?
cout << r1.is_larger(r2) << endl;
// overloading the member function .is_larger() with >
cout << (r1 > r1) << endl;
cout << (r1 > r2) << endl;
return 0;
}
#pragma once
class Point
{
private:
double x;
double y;
public:
Point() { x = y = 0; }
Point(double a, double b) { x = a; y = b; }
Point(Point& pt) { x = pt.x; y = pt.y; }
void move(double a, double b)
{
x += a;
y += b;
}
};
class Rectangle
{
private:
Point p;
double w;
double h;
public:
Rectangle() : p(0, 0), w(1), h(1) { }
Rectangle(Point pt, double a, double b)
{
p = pt;
w = a;
h = b;
}
void move(double a, double b)
{
p.move(a, b);
}
double area()
{
return w * h;
}
bool is_larger(Rectangle& another)
{
return area() > another.area();
}
bool operator>(Rectangle& another)
{
return is_larger(another);
}
};
1
0.87
1
0
1
Press any key to continue . . .