简介: CSDN博客专家,专注Android/Linux系统,分享多mic语音方案、音视频、编解码等技术,与大家一起成长!
优质专栏:Audio工程师进阶系列【原创干货持续更新中……】🚀
人生格言: 人生从来没有捷径,只有行动才是治疗恐惧和懒惰的唯一良药.
本篇目的:理解C++之struct匿名结构体用法。
C++中的“匿名结构体”通常也被称为“无名结构体”或“未命名结构体”,是指在结构体定义时没有给予其一个特定的名称。它与普通的有名结构体相比,在语法上有一些差异和特殊用法。
struct
关键字,但不提供名称。定义匿名结构体主要用于临时的数据组织和封装,通常作为其他数据类型(如类、其他结构体)的成员。struct {
int id;
std::string name;
} student;
在上述代码中,我们使用匿名结构体定义了一个名为student
的变量。
// 使用花括号初始化器
student = { 1, "John" };
// 使用成员初始化列表
student = { .id = 2, .name = "Alice" };
.
):std::cout << "ID: " << student.id << ", Name: " << student.name << std::endl;
class MyClass {
public:
struct {
int day;
int month;
int year;
} birthdate;
};
{
struct {
int id;
std::string name;
} student;
student.id = 1;
student.name = "John";
std::cout << "ID: " << student.id << ", Name: " << student.name << std::endl;
}
#include
using namespace std;
struct {
int x;
int y;
} point;
int main() {
point.x = 3;
point.y = 4;
cout << "坐标:(" << point.x << ", " << point.y << ")" << endl;
return 0;
}
#include
using namespace std;
struct {
string name;
int score;
} student;
int main() {
student.name = "张三";
student.score = 90;
cout << "姓名: " << student.name << endl;
cout << "成绩: " << student.score << endl;
return 0;
}
#include
using namespace std;
struct {
int width;
int height;
} rectangle;
int main() {
rectangle.width = 5;
rectangle.height = 7;
cout << "宽度: " << rectangle.width << endl;
cout << "高度: " << rectangle.height << endl;
return 0;
}
#include
using namespace std;
struct {
struct {
int day;
int month;
int year;
} date;
struct {
int hour;
int minute;
int second;
} time;
} datetime;
int main() {
datetime.date.day = 10;
datetime.date.month = 12;
datetime.date.year = 2021;
datetime.time.hour = 9;
datetime.time.minute = 30;
datetime.time.second = 15;
cout << "日期:" << datetime.date.year << "-" << datetime.date.month << "-" << datetime.date.day << endl;
cout << "时间:" << datetime.time.hour << ":" << datetime.time.minute << ":" << datetime.time.second << endl;
return 0;
}
#include
using namespace std;
struct {
string name;
int age;
string department;
} employee;
int main() {
employee.name = "李四";
employee.age = 28;
employee.department = "销售部门";
cout << "姓名: " << employee.name << endl;
cout << "年龄: " << employee.age << endl;
cout << "部门: " << employee.department << endl;
return 0;
}
#include
typedef void (*HWC2_PFN_CREATE_LAYER)();
struct {
HWC2_PFN_CREATE_LAYER createLayer;
} mDispatch = {};
void myCreateLayer() {
printf("Creating a layer...\n");
}
int main() {
mDispatch.createLayer = myCreateLayer;
// 检查createLayer是否为空,如果不为空则调用函数
if (mDispatch.createLayer != NULL) {
printf("Calling createLayer function...\n");
mDispatch.createLayer();
} else {
printf("createLayer function is not assigned.\n");
}
return 0;
}