Advertisement
wendy890711

虛擬函式

May 6th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <iostream>
  3. using namespace std;
  4.  
  5.  
  6. class Shape
  7. {
  8. public:
  9. virtual double area(){ return 0; }
  10. Shape(double x = 0, double y = 0){ this->x = x; this->y = y; }
  11. protected:
  12. double x, y;
  13. };
  14.  
  15. class Circle :virtual public Shape
  16. {
  17. public:
  18. Circle(double x = 0, double y = 0, double radius = 0) :Shape(x, y){ r = radius; }
  19. double area(){ return r*r*3.14159; }
  20. private:
  21. double r;
  22. };
  23.  
  24. class Rectangle : virtual public Shape
  25. {
  26. public:
  27. Rectangle(double x = 0, double y = 0, double x1 = 1, double y1 = 1) :Shape(x, y){ this->x1 = x1; this->y1 = y1; }
  28. double area(){ return (x1 - x)*(y1 - y); }
  29. private:
  30. double x1, y1;
  31. };
  32.  
  33. void main()
  34. {
  35. Shape*sp[3] = { new Shape(), new Circle(1, 1, 3), new Rectangle(1, 2, 3, 4) };
  36. for (int i = 0; i < 3; i++)
  37. cout << sp[i]->area() << endl;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement