类和对象-封装-案例1-立方体类

文章描述了一个名为Cobe的类,用于表示立方体,包含设置和获取长宽高、计算面积和体积的方法。还定义了判断两个立方体是否相等的两种方法:直接比较和通过成员函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
using namespace std;

class Cobe {


public:
    //设置长
    void setL(int l) {
        m_L = l;
    }

    //设置宽
    void setW(int w) {
        m_W = w;
    }

    //设置高
    void setH(int h) {
        m_H = h;
    }


    //获取长
    int  getL() {

        return m_L;
    }

    //获取宽
    int  getW() {

        return m_W;
    }

    //获取高
    int  getH() {

        return m_H;
    }

    //获取立方体面积
    int getS() {

        return 2 * (m_L * m_W +  m_L * m_H +  m_W *m_H);
    }
    //获取立方体的体积
    int getV() {

        return m_L * m_W * m_H;
    }
    bool isSameByClass(Cobe& c) {
        if (m_L== c.getL() && m_W == c.getW() && m_H== c.getH())
        {

            return true;
        }
        return false;
    }

private:

    int m_L;//长
    int m_W;//宽
    int m_H;//高

};

//判断两个立方体是否相等
bool isSame(Cobe &c1,Cobe &c2) 
{
    //相等返回真
    if (c1.getL() == c2.getL() && c1.getW() == c2.getW () && c1.getH() == c2.getH())
    {

        return true;
    }
    return false;
}

int main(){
    Cobe c1;
    c1.setL(10);
    c1.setW(10);
    c1.setH(10);
    cout<<"c1面积为:"<<c1.getS()<<endl;
    cout<<"c2体积为:"<<c1.getV()<<endl;
    Cobe c2;
    c2.setL(10);
    c2.setW(10);
    c2.setH(10);
    
    bool ret= isSame(c1, c2);
    if (ret) {
        cout << "c1和c2相等" << endl;

    }
    else {
        cout << "不相等" << endl;
    }
    
    
    ret = c1.isSameByClass(c2);
    if (ret) {
        cout << "成员函数判断:c1和c2相等" << endl;

    }
    else {
        cout << "成员函数判断不相等" << endl;
    }
    system("pause");
    return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值