目录
1.面向对象的三大特点
2.C++创建的类的基本格式
2.1 类
2.2 访问权限问题
3.实战演练
4. struct和class的区别
5. 成员属性设置私有化
6. 放松时刻
1.面向对象的三大特点
封装,继承,多态。
2.C++创建的类的基本格式
class 类名
{
public: // 公共权限
protected: // 保护权限
private: // 私有权限
// 属性
...
// 行为
...
}
2.1 类
类中的属性和行为,我们统一成为,成员。
属性也称为,成员属性,成员变量;
行为也称为,成员函数,成员方法。
2.2 访问权限问题
public: // 公共权限,成员,类内可以访问,类外可以访问;
protected: // 保护权限,成员,类内可以访问, 类外不可以访问;子类可以访问父类的部分;
private: // 私有权限成员,类内可以访问, 类外不可以访问;子类不可以访问父类的部分。
后两者区别在继承关系中经常使用。此处不做深入探讨。
3.实战演练
题目:实现学生信息的录入和打印输出。
分析:根据用户输入动态new出num个示例,然后通过循环调用行为GetValue()来录入信息,之后通过循环调用PrintInfor()来打印学生信息。
#include#include using namespace std; class Student { // 属性 public: int no; string name; // 行为 void GetValue() { cout << "请输入学生学号:"; cin >> no; cout << "请输入学生姓名:"; cin >> name; } void PrintInfor() { cout << "学生学号:" << no; cout << "学生姓名:" << name << endl; } }; int main() { int num; cout << "请输入学生个数:"; cin >> num; Student* stu = new(Student[num]); for (int i = 0; i < num; i++) { stu[i].GetValue(); } cout << "学生信息是" << endl; for (int i = 0; i < num; i++) { stu[i].PrintInfor(); } system("pause"); return 0; }
程序改进:对于录入信息部分,还可以做出如下修改:
// 在类中修改方法GetValue()
...
void GetValue(int input_no, string input_name){
no = input_no;
name = input_name;
}
...
// 修改代码
int no;
string name;
for(int i = 0; i < num; i++) {
cin >> no;
cin >> name;
stu[i].GetValue(no, name);
}
4. struct和class的区别
struct的默认权限是public,class的默认权限是private;
5. 成员属性设置私有化
1. 对于成员属性设置为私有化,可以实现人为对属性的读写权限的控制(即,是否对外界提供结构来修改成员属性值);
2. 对于可写的属性,便于判断其数据有效性。如:
程序分析: 对于一个类,对外提供了姓名name的读写接口,年龄age的读写接口,性别sex的写入接口,职业pos的读接口;然后对年龄,性别写入加以限制。实例化num个对象后,通过for循环对各个实例进行初始化。
#include#include using namespace std; class Student { public: void setName(string input) { // name 写 name = input; } string GetName() { // name 读 return name; } int setAge(int input) { // age 写 if (input > 100 || input < 0) { cout << "t年龄输入不合法!" << endl; input = -1; return 0; } age = input; return 1; } int GetAge() { // age 读 return age; } int setSex(char* input) { // sex 写 if (!strcmp(input, "男") || !strcmp(input, "女")|| !strcmp(input, "人妖")) { if (!strcmp(input, "人妖")) { cout << "********恭喜你解锁隐藏性别********" << endl; } *sex = *input; return 1; } cout << "t输入非法!" << endl; return 0; } string GetPos() { // pos 读 return pos; } private: string name; // 可读可写 int age = 0; // 可读可写 char sex[5] = "未知"; // 只写 string pos = "学生"; // 只读 }; int main() { string name, pos; char sex[5]; int age, num; cout << "输入计划录入的人数:"; cin >> num; Student *stu = new(Student[num]); for (int i = 0; i < num; i++) { cout << "第" << i + 1 << "位:" << endl; cout << "t输入姓名:"; cin >> name; stu[i].setName(name); cout << "t输入年龄:"; cin >> age; if (!(stu[i].setAge(age))) { cout << "t设置失败!" << endl; } cout << "t输入性别:"; cin >> sex; stu[i].setSex(sex); cout << "t输入职位:"; cin >> pos; } for (int i = 0; i < num; i++) { cout << "n输出第" << i + 1 << "位学生信息:n" << endl; cout << "t姓名->" << stu[i].GetName() << endl; cout << "t年龄->" << stu[i].GetAge() << endl; cout << "t职位->" << stu[i].GetPos() << endl; } return 0; }
6. 放松时刻



