Skip to content

Latest commit

 

History

History
232 lines (177 loc) · 3.27 KB

11_类.md

File metadata and controls

232 lines (177 loc) · 3.27 KB

1.1 封装的意义

  • 语法: class 类名{ 访问权限 属性 / 行为 }
  • 访问权限:
    • public 公共权限
    • protected 保护权限
    • private 私有权限
/// <summary>
/// TODO: 属性: 姓名 学号   行为:显示姓名、学号,赋值姓名、学号
/// </summary>
class Student {

protected:
	/// <summary>
	/// 姓名
	/// </summary>
	string name;
	/// <summary>
	/// 学号
	/// </summary>
	int number;

public:
	void showName() {
		cout << name << endl;
	};

	void showNumber() {
		cout << number << endl;
	}

	void setName(string name) {
		name = name;
	};

	void setNumber(int num) {
		number = num;
	};
};



int main() {

	Student s;
	s.setName("小明");
	s.setNumber(1);

	s.showName();
	s.showNumber();

	system("pause");

	return 0;
}

1.2 struct 和 class 区别

  • 在 C++ 中 struct 和 class 唯一的 区别 就在于 默认的访问权限不同
    • struct 默认权限是公共
    • class 默认权限为私有

1.3 成员属性设置为私有

  • 将所有成员属性设置为私有,可以自己控制读写权限
  • 对于写权限,可以检测数据的有效性
/// <summary>
/// TODO: 属性: 姓名 学号   行为:显示姓名、学号,赋值姓名、学号
/// </summary>
class Student {

protected:
	/// <summary>
	/// 姓名
	/// </summary>
	string name;
	/// <summary>
	/// 学号
	/// </summary>
	int age = 0;

public:

	void getName() {
		cout << name << endl;
	};

	void setName(string value) {
		name = value;
	};

	void setAge(int value) {
		if (value < 0 || value>120) {
			cout << "年龄超出范围" << endl;
			return;
		}
		else {
			age = value;
		}
	}
};



int main() {

	Student t;
	t.setAge(1200);

	system("pause");

	return 0;
}
/// <summary>
/// TODO: 求出立方体类(Cube)的面积和体积
/// </summary>
class Cube {

private:
	/// <summary>
	/// 长
	/// </summary>
	double l;
	/// <summary>
	/// 宽
	/// </summary>
	double w;
	/// <summary>
	/// 高
	/// </summary>
	double h;

public:

	void setLenght(double value = 0) {
		if (value <= 0) {
			cout << "参数不满足条件" << endl;
			return;
		}
		l = value;
	}
	void setWidth(double value = 0) {
		if (value <= 0) {
			cout << "参数不满足条件" << endl;
			return;
		}
		w = value;
	}
	void setHeight(double value = 0) {
		if (value <= 0) {
			cout << "参数不满足条件" << endl;
			return;
		}
		h = value;
	}

	void setInfo(double lenght = 0, double width = 0, double height = 0)
	{
		if (lenght <= 0 || width <= 0 || height <= 0) {
			cout << "参数不满足条件" << endl;
			return;
		}

		l = lenght;
		w = width;
		h = height;
	}

	/// <summary>
	/// 面积
	/// </summary>
	void calculteArea() {
		cout << l * w * 2 + l * h * 2 + h * w * 2 << endl;
	}

	/// <summary>
	/// 体积
	/// </summary>
	void calculteVolume()
	{
		cout << l * w * h << endl;
	}

	bool isEqual(Cube& c)
	{
		if (c.l == l && c.w == w && c.h == h) {
			return true;
		}
		return false;
	}
};



int main() {

	Cube cube;

	cube.setInfo(1, 2, 3);

	cube.calculteArea();

	cube.calculteVolume();

	Cube cube2;

	cube2.setInfo(1, 2, 3);

	Cube cube3;

	cube3.setInfo(2, 2, 3);

	bool flag = cube.isEqual(cube2);
	cout << flag << endl;

	flag = cube.isEqual(cube3);
	cout << flag << endl;

	system("pause");

	return 0;
}