一、结构体基本使用
#include <iostream>
#include <string>
using namespace std;
struct Person {
string name;
int age;
float height;
};
int main() {
// 传统初始化
Person p1;
p1.name = "张三";
p1.age = 25;
p1.height = 1.75f;
cout << p1.name << endl;
cout << p1.age << endl;
cout << p1.height << endl;
// 直接初始化
Person p2{ "李四" , 30 , 1.8f };
cout << p2.name << endl;
cout << p2.age << endl;
cout << p2.height << endl;
return 0;
}
# 输出结果
张三
25
1.75
李四
30
1.8
二、构造体高级特性
1、成员函数
#include <iostream>
#include <string>
using namespace std;
struct Rectangle {
int width, height;
int area() {
return width * height;
}
};
int main() {
Rectangle rectangle;
rectangle.width = 10;
rectangle.height = 10;
cout << rectangle.area() << endl;
return 0;
}
# 输出结果
100
2、访问控制
#include <iostream>
#include <string>
using namespace std;
struct SecureData {
private:
string secret;
public:
void setSecret(string s) { secret = s; }
string getSecret() const { return secret; }
};
int main() {
SecureData secureData;
secureData.setSecret("123");
cout << secureData.getSecret() << endl;
return 0;
}
# 输出结果
123
3、作为函数参数和返回值
#include <iostream>
#include <string>
using namespace std;
struct Person {
string name;
int age;
float height;
};
void printPerson(Person person) {
cout << person.name << endl;
cout << person.age << endl;
cout << person.height << endl;
}
void changePerson(Person &person) {
person.name = "李四";
person.age = 30;
person.height = 1.8f;
}
int main() {
Person p1;
p1.name = "张三";
p1.age = 25;
p1.height = 1.75f;
printPerson(p1);
changePerson(p1);
printPerson(p1);
return 0;
}
# 输出结果
张三
25
1.75
李四
30
1.8
三、结构体构造函数
1、默认构造函数(无参)
#include <iostream>
#include <string>
using namespace std;
struct Person {
string name;
int age;
float height;
// 默认构造函数(无参数)
Person() {
name = "Unknown";
age = 0;
height = 0.0f;
}
};
int main() {
Person p1;
cout << p1.name << endl;
cout << p1.age << endl;
cout << p1.height << endl;
return 0;
}
# 输出结果
Unknown
0
0
2、带参构造函数
#include <iostream>
#include <string>
using namespace std;
struct Person {
string name;
int age;
float height;
// 带参构造函数
Person(string n, int a, float h) {
name = n;
age = a;
height = h;
}
};
int main() {
Person p1("Alice", 25, 1.68f);
cout << p1.name << endl;
cout << p1.age << endl;
cout << p1.height << endl;
return 0;
}
# 输出结果
Alice
25
1.68
四、结构体析构函数
1、基本介绍
-
在 C++ 中,析构函数(Destructor)是一种特殊的成员函数,用于在对象生命周期结束时自动释放资源,例如,动态内存、文件句柄、网络连接等
-
析构函数的名称是在类名前加
~
,没有返回类型,也不接受参数
2、演示
#include <iostream>
#include <string>
using namespace std;
struct Person {
string name;
int age;
float height;
Person(string n, int a, float h) {
name = n;
age = a;
height = h;
}
~Person() {
std::cout << "Person " << name << " is being destroyed." << std::endl;
}
};
int main() {
Person p1("Alice", 25, 1.68f);
return 0;
}
# 输出结果
Person Alice is being destroyed.