題目要求
- 定義
Student 類:學號、姓名、年齡 3 個數據成員;構造/析構函數實現輸入輸出;若干成員函數。
- 主函數使用類:賦值、輸出數據。
- 建立對象數組存 5 個學生,用指針輸出第 1、3、5 個學生數據。
- 文件劃分:
student.h(類聲明)、student.cpp(實現)、_tmain.cpp(主函數)。
文件劃分與完整代碼
student.h
#ifndef STUDENT_H
#define STUDENT_H
#include <string>
class Student {
private:
int id;
std::string name;
int age;
public:
// 構造函數:輸入初始化
Student(int id = 0, const std::string& name = "", int age = 0);
// 析構函數:輸出銷毀信息
~Student();
void setData(int id, const std::string& name, int age);
void display() const;
int getId() const { return id; }
};
#endif
student.cpp
#include "student.h"
#include <iostream>
Student::Student(int id, const std::string& name, int age)
: id(id), name(name), age(age) {
std::cout << "構造學生: " << name << std::endl;
}
Student::~Student() {
std::cout << "析構學生: " << name << std::endl;
}
void Student::setData(int id, const std::string& name, int age) {
this->id = id;
this->name = name;
this->age = age;
}
void Student::display() const {
std::cout << "學號: " << id << ", 姓名: " << name << ", 年齡: " << age << std::endl;
}
_tmain.cpp
#include "student.h"
#include <iostream>
int main() {
// 1. 單個對象演示
Student s1(1, "張三", 20);
s1.display();
// 2. 對象數組存 5 個學生
Student students[5] = {
Student(1, "張三", 20),
Student(2, "李四", 21),
Student(3, "王五", 22),
Student(4, "趙六", 23),
Student(5, "錢七", 24)
};
// 3. 指針遍歷輸出第 1、3、5 個(下標 0,2,4)
Student* ptr = students; // 指向數組首元素
std::cout << "=== 指針訪問第 1、3、5 個學生 ===" << std::endl;
for (int i = 0; i < 5; i += 2) {
(ptr + i)->display(); // 指針算術 + 成員訪問
}
// 4. 也可用下標方式驗證
std::cout << "=== 下標方式驗證 ===" << std::endl;
for (int i = 0; i < 5; i += 2) {
students[i].display();
}
return 0;
}
編譯運行命令
g++ student.cpp _tmain.cpp -o student_demo
./student_demo
關鍵知識點總結
- 構造/析構:自動完成初始化/清理,此處用於演示輸入輸出。
- 對象數組:
Student students[5] 連續存儲 5 個對象,調用 5 次構造、5 次析構。
- 指針算術:
ptr + i 偏移 i * sizeof(Student) 字節,指向第 i 個對象。
- 文件分離:頭文件聲明、源文件實現、主文件使用,符合工程規範。
- const 正確性:
display() const 承諾不修改成員,可被常對象調用。