定义结构的格式是
struct Tag {
Members
};
其中Tag是整个结构类型的名称,而Member是该结构内的变量。要实际创建一个结构,语法是
struct Tag name_of_single_structure;
要访问结构的变量,它会
name_of_single_structure.name_of_variable;
例如:
struct example {
int x;
};
struct example an_example; //Treating it like a normal variable type
an_example.x = 33; //How to access its members
这是一个示例程序:
struct database {
int id_number;
int age;
float salary;
};
int main()
{
database employee; //There is now an employee variable that has modifiable
// variables inside it.
employee.age = 22;
employee.id_number = 1;
employee.salary = 12000.21;
}
struct数据库声明该数据库中具有年龄,id_number和salary三个变量。您可以像使用int这样的变量类型一样使用数据库。您可以像上面一样创建具有数据库类型的员工。然后,要对其进行修改,您可以用“员工”来调用所有内容。在它前面。您还可以通过将函数的返回类型定义为结构类型来从函数返回结构。例如:
1个
database fn();
我也只会谈一点工会。联合类似于结构,除了所有变量共享相同的内存。声明联合后,编译器会为联合中最大的数据类型分配足够的内存。这就像一个巨大的存储箱,您可以在其中存储一个大项目或一个小项目,但不能同时存储这两个项目。
这 ‘。’ 运算符还用于访问并集内的不同变量。
最后一点,如果您希望有一个指向结构的指针,以实际访问存储在所指向的结构中的信息,请使用->运算符代替。操作员。关于指针的所有要点仍然适用。
一个简单的例子:
#include <iostream>
using namespace std;
struct xampl {
int x;
};
int main()
{
xampl structure;
xampl *ptr;
structure.x = 12;
ptr = &structure; // Yes, you need the & when dealing with structures
// and using pointers to them
cout<< ptr->x; // The -> acts somewhat like the * when used with pointers
// It says, get whatever is at that memory address
// Not "get what that memory address is"
cin.get();
}