鱼C论坛

 找回密码
 立即注册
查看: 1998|回复: 0

[技术交流] C++继承

[复制链接]
发表于 2019-11-29 00:31:49 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. #include <iostream>
  2. #include <cmath>
  3. using uint = unsigned int;
  4. class shape
  5. {
  6. private:
  7.     unsigned int high;
  8.     unsigned int bottom;

  9. public:
  10.     shape(uint l = 0, uint w = 0) : high(l), bottom(w) {}
  11.     shape(shape &sh) : high(sh.high), bottom(sh.bottom) {}
  12.     virtual double area() { return high * bottom; }
  13.     virtual uint girth() { return 2 * (high + bottom); }
  14.     virtual ~shape() { std::cout << "基类" << std::endl; }
  15. };
  16. class parallelogram : public shape
  17. {
  18. public:
  19.     parallelogram(uint pl = 0, uint pw = 0) : shape(pl, pw) {}
  20.     ~parallelogram() { std::cout << "四边形" << std::endl; }
  21. };
  22. class triangle : public shape
  23. {
  24. private:
  25.     uint A, B, C;

  26. public:
  27.     triangle(uint a = 0, uint b = 0, uint c = 0) : A(a), B(b), C(c) {}
  28.     triangle(triangle &t) : A(t.A), B(t.B), C(t.C) {}
  29.     bool isEffTri()
  30.     {
  31.         bool t = true;
  32.         if (A + B <= C || A + C <= B || B + C <= A)
  33.         {
  34.             t = false;
  35.         }
  36.         return t;
  37.     }
  38.     virtual uint girth()
  39.     {
  40.         return A + B + C;
  41.     }
  42.     virtual double area()
  43.     {
  44.         double t = this->girth() / 2;
  45.         return sqrt(t * (t - A) * (t - B) * (t - C));
  46.     }
  47.     ~triangle() { std::cout << "三角形" << std::endl; }
  48. };
  49. int main(int argc, char const *argv[])
  50. {
  51.     parallelogram a = {5, 6};
  52.     triangle c = {3, 4, 5};
  53.     shape &b = a;
  54.     shape &d = c;
  55.     std::cout << b.area() << " " << b.girth() << std::endl;
  56.     std::cout << std::boolalpha << c.isEffTri() << "\n"
  57.               << d.area() << " " << d.girth() << std::endl;
  58.     return 0;
  59. }
复制代码

=============================================
Microsoft Windows [版本 10.0.18363.476]
(c) 2019 Microsoft Corporation。保留所有权利。

E:\Users\admin\Documents\VScode\Code>c:\Users\admin\.vscode\extensions\ms-vscode.cpptools-0.26.1\debugAdapters\bin\WindowsDebugLauncher.exe --stdin=Microsoft-MIEngine-In-xi5u5r2f.pvc --stdout=Microsoft-MIEngine-Out-f0v3iqur.5cy --stderr=Microsoft-MIEngine-Error-jarwxi4b.f01 --pid=Microsoft-MIEngine-Pid-za2qqxtf.z4l --dbgExe=D:\MinGW\bin\gdb.exe --interpreter=mi
30 22
true
6 12
三角形
基类
四边形
基类


E:\Users\admin\Documents\VScode\Code>
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-7 16:39

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表