鱼C论坛

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

[技术交流] C++继承

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

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

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

x
#include <iostream>
#include <cmath>
using uint = unsigned int;
class shape
{
private:
    unsigned int high;
    unsigned int bottom;

public:
    shape(uint l = 0, uint w = 0) : high(l), bottom(w) {}
    shape(shape &sh) : high(sh.high), bottom(sh.bottom) {}
    virtual double area() { return high * bottom; }
    virtual uint girth() { return 2 * (high + bottom); }
    virtual ~shape() { std::cout << "基类" << std::endl; }
};
class parallelogram : public shape
{
public:
    parallelogram(uint pl = 0, uint pw = 0) : shape(pl, pw) {}
    ~parallelogram() { std::cout << "四边形" << std::endl; }
};
class triangle : public shape
{
private:
    uint A, B, C;

public:
    triangle(uint a = 0, uint b = 0, uint c = 0) : A(a), B(b), C(c) {}
    triangle(triangle &t) : A(t.A), B(t.B), C(t.C) {}
    bool isEffTri()
    {
        bool t = true;
        if (A + B <= C || A + C <= B || B + C <= A)
        {
            t = false;
        }
        return t;
    }
    virtual uint girth()
    {
        return A + B + C;
    }
    virtual double area()
    {
        double t = this->girth() / 2;
        return sqrt(t * (t - A) * (t - B) * (t - C));
    }
    ~triangle() { std::cout << "三角形" << std::endl; }
};
int main(int argc, char const *argv[])
{
    parallelogram a = {5, 6};
    triangle c = {3, 4, 5};
    shape &b = a;
    shape &d = c;
    std::cout << b.area() << " " << b.girth() << std::endl;
    std::cout << std::boolalpha << c.isEffTri() << "\n"
              << d.area() << " " << d.girth() << std::endl;
    return 0;
}
=============================================
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>
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-1-16 11:13

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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