C++结构体详解(已完结)
Emily1234
·
·
算法·理论
#include <iostream>
#include <string>
using namespace std;
// 定义Student结构体
struct Student {
// 1. 静态成员变量:统计对象数量
static int count; // 声明静态成员变量,所有Student对象共享
// 2. 普通数据成员
string name;
int age;
float score;
// 3. 带默认参数的构造函数
Student(string n = "未知", int a = 0, float s = 0.0) : name(n), age(a), score(s) {
count++; // 对象创建时,计数+1
cout << "构造函数执行:" << name << ",当前数量:" << count << endl;
}
// 4. 拷贝构造函数
Student(const Student& other) {
// 将被拷贝对象的成员赋值给新对象
this->name = other.name;
this->age = other.age;
this->score = other.score;
count++; // 拷贝生成新对象,计数+1
cout << "拷贝构造函数执行:" << name << ",当前数量:" << count << endl;
}
// 5. 析构函数
~Student() {
count--; // 对象销毁时,计数-1
cout << "析构函数执行:" << name << ",当前数量:" << count << endl;
}
// 6. 静态成员函数:获取当前对象数量
static int getCount() {
return count; // 静态成员函数仅能访问静态成员变量
}
};
// 7. 静态成员变量的初始化:必须在结构体外部定义并赋值
int Student::count = 0;
// 主函数:测试对象的创建、拷贝、销毁
int main() {
cout << "===== 程序开始,初始对象数量:" << Student::getCount() << " =====" << endl;
// 场景1:创建普通局部对象
Student stu1("张三", 18, 92.5);
cout << "创建stu1后,数量:" << Student::getCount() << endl;
Student stu2("李四", 19, 88.0);
cout << "创建stu2后,数量:" << Student::getCount() << endl;
// 场景2:创建代码块内的局部对象(出块自动销毁)
{
Student stu3("王五", 20, 95.0);
cout << "创建stu3后,数量:" << Student::getCount() << endl;
} // stu3出作用域,析构函数自动执行
cout << "stu3销毁后,数量:" << Student::getCount() << endl;
// 场景3:对象拷贝(触发拷贝构造函数)
Student stu4 = stu1; // 用stu1拷贝生成stu4
cout << "拷贝stu1生成stu4后,数量:" << Student::getCount() << endl;
// 场景4:创建动态对象(堆区)
Student* pStu = new Student("赵六", 21, 90.0); // new触发构造函数
cout << "创建动态对象后,数量:" << Student::getCount() << endl;
// 场景5:释放动态对象(手动delete)
delete pStu; // delete触发析构函数
cout << "释放动态对象后,数量:" << Student::getCount() << endl;
cout << "===== 程序结束,最终对象数量:" << Student::getCount() << " =====" << endl;
return 0;
}