C++ 中 Class 的基础使用方法
类、对象和成员的关系
类是模板 → 对象是实例 → 成员是对象的组成部分
最简单的例子(狗与狗叫)
#include <iostream>
using namespace std;
// 【类】= 模板/图纸
class Dog {
public:
// 【成员变量】= 属性
string name; // 名字
int age; // 年龄
// 【成员函数】= 行为
void bark() {
cout << name << "(" << age << " 岁)汪汪叫!" << endl;
}
};
int main() {
// 【对象】= 具体的狗
Dog dog1; // 创建对象1
dog1.name = "旺财";
dog1.age = 3;
Dog dog2; // 创建对象2
dog2.name = "小白";
dog2.age = 2;
// 使用对象的成员
dog1.bark(); // 旺财(3 岁)汪汪叫!
dog2.bark(); // 小白(2 岁)汪汪叫!
return 0;
}
输出
旺财(3 岁)汪汪叫!
小白(2 岁)汪汪叫!
另一份代码示例(学生信息与成绩)
#include <iostream>
#include <string>
using namespace std;
class Score { // 定义一个“分数”类,类的名字叫 Score
public:
int Chinese;
int Maths;
int English;
void inputScore(int a, int b, int c){ // 在 Score 类里定义一个“设置器”成员函数,用于方便地定义一个 Score 类的对象
Chinese = a;
Maths = b;
English = c;
}
void print();
};
void Score::print(){ // 类外定义,注意加上类名!“::”是作用域解析运算符(scope resolution operator),并不表示命名空间。
/*
打印语数英成绩
*/
cout << "Chinese:\t" << Chinese << endl;
cout << "Maths:\t\t" << Maths << endl;
cout << "English:\t" << English;
}
class Student{ // 定义一个“学生”类,类的名字叫 Student
private:
Score score;
public:
string id;
string name;
void setInfo(string id1, string name1, Score score1){
/*
在 Student 类里定义一个“设置器”成员函数,
用于方便地定义一个 Student 类的对象的学号(id)、姓名(name)和分数(score)
*/
id = id1;
name = name1;
score = score1;
}
void print(){
/*
打印该学生的所有信息
*/
cout << "ID:\t\t" << id << endl;
cout << "Name:\t\t" << name << endl;
/*
调用 Score 类里定义的 print() 函数,用于输出该学生的分数信息
注意,这里的 score 是一个 Score 类的对象
*/
score.print();
cout << endl;
}
};
int main(){
// 设置学生的分数
Score wenshuScore;
wenshuScore.inputScore(109, 105, 120);
// 设置学生的信息,包括上一步已经设置好的学生的分数
Student wenshu;
/*
调用“设置器”成员函数来为 wenshu 这个 Student 类的对象设置信息
这里用了“分数”类的对象 wenshuScore 来为 wenshu 里的“分数”成员 score 赋值
*/
wenshu.setInfo("028125297", "温树", wenshuScore);
// 打印学生的所有信息
wenshu.print();
cout << endl;
// 单独打印分数信息
cout << "单独打印 "<< wenshu.name <<" 的成绩:" << endl;
wenshuScore.print();
cout << endl;
return 0;
}
输出
ID: 028125297
Name: 温树
Chinese: 109
Maths: 105
English: 120
单独打印 温树 的成绩:
Chinese: 109
Maths: 105
English: 120