1.封装
两层含义:
(1)把事物的属性和方法结合成个整体。
(2)对类的属性和方法进行访问控制,对不信的进行信息屏蔽。
2.访问控制
控制分为 类的内部,类的外部。
public 修饰的成员,可在内部和外部访问。
private 修饰的成员,只能在内部访问。

封装就像一个手表,里面有很复杂的功能,但输出只有表盘,输入只能转转轴。
3. 类与对象
抽象一个类,用类去定义对象。
类是数据类型,是抽象的,对象是具体的变量,占用内存空间。
4. struct 和 class 关键字的区别
在 struct 定义的类中,所有成员的默认访问控制为 public
在 class 中 为 private。
5. 练习
(1)设计立方体类(cube),求出立方体的面积和体积,求两个立方体,是否相等。
- #include <iostream>
- using namespace std;
- class cube{
- private:
- double length;
- double high;
- double width;
- public:
- double getLength()
- {
- return length;
- }
- double getHigh()
- {
- return high;
- }
- double getWidth()
- {
- return width;
- }
- void setLength(double length)
- {
- this->length = length;
- }
- void setWidth(double width)
- {
- this->width = width;
- }
- void setHigh(double high)
- {
- this->high = high;
- }
- double getArea()
- {
- return 0;
- }
- double getVolume()
- {
- return 0;
- }
- bool isEqualCube1(class cube c);
- bool isEqualCube2(class cube *c);
- bool isEqualCube3(class cube &c);
- protected:
- };
- bool cube::isEqualCube1(class cube c)
- {
- /* 下面的函数调用体现出封装的强大,因为复制的参数,不仅带有属性,还有函数 */
- if (c.getLength() == this->length &&
- c.getHigh() == this->high &&
- c.getWidth() == this->width)
- return true;
- else
- return false;
- }
- bool cube::isEqualCube2(class cube *c)
- {
- if (c->getLength() == this->length &&
- c->getHigh() == this->high &&
- c->getWidth() == this->width)
- return true;
- else
- return false;
- return true;
- }
- bool cube::isEqualCube3(class cube &c)
- {
- if (c.getLength() == this->length &&
- c.getHigh() == this->high &&
- c.getWidth() == this->width)
- return true;
- else
- return false;
- }
- void main(void)
- {
- class cube c1, c2;
- c1.setHigh(1);
- c1.setLength(1);
- c1.setWidth(1);
- c2.setHigh(2);
- c2.setLength(2);
- c2.setWidth(2);
- cout << "c1's area = " << c1.getArea() << endl;;
- cout << "c2's volume = " << c2.getVolume() << endl;
- if (c1.isEqualCube1(c2))
- cout << "c1 == c2" << endl;
- else
- cout << "c1 != c2" << endl;
- system("pause");
- return ;
- }