c++之结构详解

来源:互联网 发布:大数据 管理咨询 编辑:程序博客网 时间:2024/05/29 03:15

声明结构的语法
有时候我们需要存储的数据信息由不同的数据类型组成。例如:一个职工的信息包括姓名,职工编号,工资,地址,电话。这时候就需要使用一个叫结构的语法,来存放这些东西。
结构声明是放在所有函数包括主函数之外,位于main函数之前,下面我们就来声明一个存放职工信息的数据结构。

#include<iostream>using namespace std;struct Employee   //声明一个结构{    char name[20];     //姓名    long code;         //职工编号    double salary;     //职工工资    char address[50];   //职工地址    char phone[11];     //电话};//分号是必须的int main(){    Employee person;     //定义一个Employee结构的变量,分配变量空间,c语言中必须添加struct关键字    return 0;}

声明结构时,不分配内存,内存分配发生在这个结构的定义时。在c语言中,结构体的成员只可以是数据成员,但是在c++中对结构体进行了扩展,除了数据成员外,还可以添加函数,这里只是为了适应面向对象的程序设计的,一般如果遇到需要添加函数时,就把结构改为类了

介绍一种在声明结构同时定义变量的方式,直接看例子:

struct Employee   {    char name[20];     //姓名    long code;         //职工编号    double salary;     //职工工资    char address[50];   //职工地址    char phone[11];     //电话}person1,person2;//分号是必须的,其中person1和person2是结构体Employee的两个变量

访问结构的成员
程序中一旦通过定义相应的结构变量,分配了空间,就可以使用点操作符“.”来访问结构中的成员。

#include<iostream>using namespace std;struct weather{    double temp;  //温度    double  wind; //风力};int main(){    weather today;    today.temp = 32.2;    //作为左值    today.wind = 10.1;    cout << "Temp=" << today.temp << endl;    cout << "Wind=" << today.wind << endl;    //system("pause");      return 0;}

给结构赋值

给结构体赋值的方式好似给数组赋值一样,只是数组的每个元素的数据类型是一样的,而结构的数据类型是不一样的。

#include<iostream>using namespace std;struct weather{    double temp;  //温度    double  wind; //风力}yesterday{30.2,11.0};  //直接在定义时使用花括号进行成员的初始化int main(){    weather today{30.1,10.1};//直接在定义时使用花括号进行成员的初始化    //system("pause");      return 0;}

结构与指针
根据结构类型可以定义一个变量,一个变量就要地址,结构变量不像数组,倒是和普通的变量一样是通过“&”来取地址,然后结构指针是通过箭头操作符“->”来访问结构成员,当然还是可以用点操作符来访问结构成员,只是要先解引用。

#include<iostream>using namespace std;struct weather{    double temp;  //温度    double  wind; //风力};  int main(){    weather today{30.1,10.1};    weather * today_pointer;    today_pointer = &today;    cout << "Temp=" << today_pointer->temp << endl;    //通过“->”访问结构成员    cout << "Wind=" << (*today_pointer).wind << endl;  //通过“.”访问结构成员,但是得先解引用,还得加个括号    system("pause");      return 0;}

输出结果:
这里写图片描述

传递结构参数
(1):传递结构值,这个情况下整个结构值都将被复制到形参中。
(2):传递结构引用,这个情况只是把结构地址传递给形参,因此引用传递效率较高

#include<iostream>using namespace std;struct weather{    double temp;  //温度    double  wind; //风力};  void print(weather today)           //传递值{    cout << "我是传值:" << endl;    cout << "Temp=" << today.temp << endl;        cout << "Wind=" << today.wind << endl; }void print_quote(weather & today)    //传递引用{    cout << "我是引用:" << endl;    cout << "Temp=" << today.temp << endl;    cout << "Wind=" << today.wind << endl;}int main(){    weather today{30.1,10.1};    print(today);    print_quote(today);    system("pause");      return 0;}

输出结果:
这里写图片描述

返回结构
一个函数可以返回一个结构值,但是这是不推荐的做法,因为结构返回时,需要复制结构值给一个临时的结构变量,当结构很大时,就会影响程序的执行效率,此时就应该通过传递引用来替代返回值。

0 0
原创粉丝点击