C++面向对象的三大特性为:==封装、继承、多态==
C++认为==万事万物都皆为对象==,对象上有其属性和行为
封装是C++面向对象三大特性之一
封装的意义:
-
将属性和行为作为一个整体,表现生活中的事物
-
将属性和行为加以权限控制
封装意义一:
在设计类的时候,属性和行为写在一起,表现事物
语法: class 类名{ 访问权限: 属性 / 行为 };
封装意义二:
类在设计时,可以把属性和行为放在不同的权限下,加以控制
访问权限有三种:
-
public 公共权限
-
protected 保护权限
-
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 默认权限为私有