C++ 学生信息类:定义和使用 Student 类
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
int age;
string name;
public:
// 带参数的构造函数
Student(int m, string n) {
age = m;
name = n;
}
// 不带参数的构造函数
Student() {
age = 0;
name = 'No';
}
// 改变数据成员值的函数
void setInfo(int m, string n) {
age = m;
name = n;
}
// 返回学生年龄
int getAge() {
return age;
}
// 返回学生姓名
string getName() {
return name;
}
};
int main() {
// 使用带参数的构造函数创建对象
Student stu1(18, 'Alice');
cout << 'Student 1 - Age: ' << stu1.getAge() << ', Name: ' << stu1.getName() << endl;
// 使用不带参数的构造函数创建对象
Student stu2;
cout << 'Student 2 - Age: ' << stu2.getAge() << ', Name: ' << stu2.getName() << endl;
// 使用setInfo函数改变数据成员值
stu2.setInfo(20, 'Bob');
cout << 'Student 2 - Age: ' << stu2.getAge() << ', Name: ' << stu2.getName() << endl;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/nja0 著作权归作者所有。请勿转载和采集!