Skip to content
On this page

Override.cpp


标签:代码片段CPP/basic  
cpp
#include <iostream>

using namespace std;

class Shape {
private:
  int round;
  int area;

public:
  Shape() {}
  Shape(int r, int a) : round(r), area(a) {}
  void virtual show() {
    cout << "round = " << round << endl;
    cout << "area = " << area << endl;
  }
};

class Rectangle : public Shape {
private:
  int width;
  int height;

public:
  Rectangle() {}
  Rectangle(int w, int h) : width(w), height(h), Shape(2 * (w + h), w * h) {}
  void show() override {
    cout << "round = " << 2 * (width + height) << endl;
    cout << "area = " << width * height << endl;
  }
};

class Circle : public Shape {
private:
  int radius;

public:
  Circle() {}
  Circle(int r) : radius(r), Shape(2 * 3.14 * r, 3.14 * r * r) {}
  void show() override {
    cout << "round = " << 2 * 3.14 * radius << endl;
    cout << "area = " << 3.14 * radius * radius << endl;
  }
};

void show_shape(Shape c) {
  Shape *p = &c;
  p->show();
}

int main() {
  Circle c(10);
  show_shape(c);
  Rectangle r(10, 20);
  show_shape(r);
  return 0;
}

Last updated: