C++学习 类

C++面向对象的三大特性为:==封装、继承、多态==

C++认为==万事万物都皆为对象==,对象上有其属性和行为

封装是C++面向对象三大特性之一

封装的意义:

  • 将属性和行为作为一个整体,表现生活中的事物

  • 将属性和行为加以权限控制

封装意义一:

在设计类的时候,属性和行为写在一起,表现事物

语法: class 类名{ 访问权限: 属性 / 行为 };

封装意义二:

类在设计时,可以把属性和行为放在不同的权限下,加以控制

访问权限有三种:

  1. public 公共权限

  2. protected 保护权限

  3. private 私有权限

#include <iostream>
using namespace std;

class Cube
{
public:
    //设置长度
	void setLength(int l)
	{
		m_Length = l;
	}
    //设置宽度
	void setWidth(int w)
	{
		m_Width = w;
	}
    //设置高度
	void setHeight(int h)
	{
		m_Height = h;
	}
    //获取长度
	int getLength()
	{
		return m_Length;
	}
    //获取宽度
	int getWidth()
	{
		return m_Width;
	}
    //获取高度
	int getHeight()
	{
		return m_Height;
	}
    
    //计算体积
	int getVolume()
	{
		return m_Length * m_Width * m_Height;
	}
    //计算表面积
	int getArea()
	{
		return 2 * (m_Length * m_Width + m_Length * m_Height + m_Width * m_Height);
	}
    //判断两个对象是否相同
	bool isSameByClass(Cube& c)
	{
		if (m_Length == c.getLength() && m_Width == c.getWidth() && m_Height == c.getHeight())
		{
			return true;
		}
		return false;
	}
private:
	int m_Length;
	int m_Width;
	int m_Height;
};

bool isSame(Cube& c1, Cube& c2)
{
	if (c1.getHeight() == c2.getHeight() && c1.getLength() == c2.getLength() && c1.getWidth() == c2.getWidth())
	{
		return true;
	}
	return false;
}

int main()
{
	Cube c1;

	c1.setHeight(10);
	c1.setLength(10);
	c1.setWidth(10);

	cout << "Volume:> " << c1.getVolume() << endl;
	cout << "Area:> " << c1.getArea() << endl;

	Cube c2;
	c2.setHeight(10);
	c2.setLength(10);
	c2.setWidth(10);

	bool ret = c1.isSameByClass(c2);
	if (ret)
	{
		cout << "Same." << endl;
	}
	else
	{
		cout << "Not Same." << endl;
	}

	system("pause");
	return 0;
}

C++中的class和C语言中的struct很像,但是二者的区别在C++中 struct和class唯一的区别就在于 默认的访问权限不同

  • struct 默认权限为公共

  • class 默认权限为私有

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值