#P2235. 语法知识.面向对象编程.1
语法知识.面向对象编程.1
重点的学习内容:
- 类的基本定义
- 构造函数
- public 和 private 关键字
- 成员函数
- 基于实例引用去访问成员变量和成员函数(用 . 运算符)
- 基于指针去访问成员变量和成员函数(用 -> 运算符)
#include<bits/stdc++.h>
using namespace std;
class Student{
public:
string name;
char gander; // ‘F’ 是女, ‘M’ 是男
Student(string a, char b, int c){
this->name = a;
this->gander = b;
this->set_score(c);
};
Student(string a, char b){ // 没有成绩信息的构造函数
this->name = a;
this->gander = b;
};
Student(){ }; // 如果没有参数,啥事都不做
void set_score(int a){
this->score = a;
}
void ask_score(){
// 询问成绩,成员函数是可以访问 private 成员的
cout<<"I am "<<this->name<<".";
// 假设成绩数据很敏感,人家不想告诉你具体多少分,只是告诉你大概情况
if(this->score >= 90)
printf("I am perfect.\n");
else if(this->score >= 80)
printf("I am good.\n");
else if(this->score>=60)
printf("I am not bad.\n");
else
printf("I don't want to tell you anything.\n");
};
private:
int score; // 成绩是不想给别人轻易访问,设置为 private 属性
};
int main(){
Student a("张三",'M',91);
a.ask_score();
// 如果直接访问 私有成员,是会出错的
// cout<<a.score<<endl;
Student b= Student("李梅",'F',89);
b.ask_score();
Student *p = new Student("吴强",'M',40);
p->ask_score();
delete p; // delete 和 new 一般是成对出现的,如果一个程序不断的 new 不 delete,内存就越占越多,总有一天会崩溃的。
return 0;
}