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

发布于:2024-04-19 ⋅ 阅读:(26) ⋅ 点赞:(0)

在这里插入图片描述

#include<bits/stdc++.h>
using namespace std;
class Cube{
	public:
	//设置长
	void setL(int l){
		m_L=l;
	} 
	//获取长
	int getL(){
		return m_L;
	}
	//设置宽 
	void setW(int w){
		m_W=w;
	}
	//获取宽 
	int getW(){
		return m_W;
	}
	//设置高 
	void setH(int h){
		m_H=h;
	}
	//获取高
	int getH(){
		return m_H;
	}
	//获取立方体面积
	int S(){
		return 2*m_L*m_W+2*m_L*m_H+2*m_W*m_H;
	}
	
	//获取立方体体积 
		int V(){
			return m_L*m_W*m_H;
		}
		
//利用成员函数判断两个立方体是否相等
bool isSameByclass(Cube &c){
	if(m_L==c.getL()&&m_H==c.getH()&&m_W==c.getW()){
		return true;
	}
	return false;
} 
	private:
		int m_L;//长 
		int m_W;//宽 
		int m_H;//高 
}; 
//利用全局函数判断两个立方体是否相等
bool isSame(Cube &c1,Cube &c2){
	if(c1.getL()==c2.getL()&&c1.getH()==c2.getH()&&c1.getW()==c2.getW()){
		return true;
	}
	return false;
} 
int main(){
	//创建立方体对象 
    Cube c1;
    
    c1.setL(10);
	c1.setW(10);
	c1.setH(10);
	cout<<"c1的面积为: "<<c1.S()<<endl;
	cout<<"c1的体积为: "<<c1.V()<<endl;
	//创建第二个立方体
	Cube c2;
    
    c2.setL(10);
	c2.setW(10);
	c2.setH(11);
	//利用全局函数判断 
	bool ret=isSame(c1,c2);
	if(ret){
		cout<<"c1和c2是相等的"<<endl;
	}
	else{
		cout<<"c1和c2是不相等的"<<endl;
	}
	//利用成员函数判断
	ret=c1.isSameByclass(c2); 
	if(ret){
		cout<<"c1和c2是相等的"<<endl;
	}
	else{
		cout<<"c1和c2是不相等的"<<endl;
	}
	return 0; 
}