一道C++题目:长方形面积相减

图片说明

题目说明如上图,这个运算符重载搞不明白啊

回答

#include <iostream>

#include <string>

using namespace std;

class Shape

{

public:

string name;

Shape(string n) : name(n) { }

virtual void area() = 0;

};

class Rectangle : public Shape

{

private:

int abs(int n) { return n > 0 ? n : -n; }

public:

int width;

int height;

Rectangle(string n, int w, int h) : Shape(n), width(w), height(h) { }

int operator -(const Rectangle r)

{

return abs(width * height - r.width * r.height);

}

void area()

{

cout << name << " " << width * height << endl;

}

};

class Circle : public Shape

{

public:

int radius;

Circle(string n, int r) : Shape(n), radius(r) { }

void area()

{

cout << name << " " << radius * radius * 3.14 << endl;

}

};

int main()

{

Rectangle r1("r1", 3, 6), r2("r2", 1, 1);

r1.area();

r2.area();

cout << r1 - r2 << endl;

cout << r2 - r1 << endl;

Circle c("c", 3);

c.area();

return 0;

}

r1 18

r2 1

17

17

c 28.26

以上是 一道C++题目:长方形面积相减 的全部内容, 来源链接: utcz.com/a/45670.html

回到顶部