C ++中的结构

定义结构的格式是

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();                    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值