C++定义一个学生类Student,属性有学号(number)、姓名(name)、年龄(age),行为是学习(Study),在主函数中定义学生类对象,为该对象所拥有的属性赋值,并输出该对象的所有信息。
时间: 2023-06-14 14:06:20 浏览: 77
以下是C++定义一个学生类Student的示例代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
// 构造函数
Student(string number, string name, int age) {
this->number = number;
this->name = name;
this->age = age;
}
// 行为:学习
void Study() {
cout << name << " is studying." << endl;
}
// 输出学生信息
void PrintInfo() {
cout << "Number: " << number << endl;
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
private:
string number; // 学号
string name; // 姓名
int age; // 年龄
};
int main() {
// 创建学生对象并初始化属性
Student stu("1001", "Tom", 18);
// 输出学生信息
stu.PrintInfo();
// 学生进行学习
stu.Study();
return 0;
}
```
运行结果:
```
Number: 1001
Name: Tom
Age: 18
Tom is studying.
```