• C++ struct 笔记(超级详细)


    今日碎碎念:我在学C语言时经常用到结构体struct,之后在写C++程序时遇到在struct中定义构造函数和成员函数的情况,这在c语言中是从未遇到过的,觉得奇怪,想到之前并没有真正系统学习C++里的struct,有必要今天详细记录一下。

       虽然今天结构体较少使用,但知道它们是什么,以及如何使用它们仍然很重要,这并不仅仅是因为可以在较老的程序中遇到它们,还因为在某些情况(这里请看二、C++ class和struct的区别)下,类的实例无法使用,这时必须使用结构体。

    目录

    一、C++ struct的用法

        1、struct是什么

         2、 struct的4种声明定义方式

         3、结构体的2种初始化方式

         4、结构体成员的访问

         5、结构体的嵌套

         6、将结构体作为参数和返回值

    二、C++ class和struct的区别

    三、C++ struct和 c struct的区别 

    四、struct计算结构体某个成员相对于结构体基址的偏移


    一、C++ struct的用法

        1、struct是什么

            struct是程序员定义的数据类型,将逻辑上连接在一起的不同类型的数据组合到一起的单元。

         2、 struct的4种声明定义方式

               a. 第一种语法表示

            struct 结构体名称
            {
               数据类型 member1;
               数据类型 member2;
            }; 

    1. #include
    2. #include
    3. using namespace std;
    4. struct SStudent
    5. {
    6. int nNo;
    7. std::string strName;
    8. };
    9. int main(int argc, char *argv[])
    10. {
    11. //使用初始化列表初始化struct
    12. struct SStudent s1 = { 1, "ying"}; //C++定义struct变量时,前面的struct可以写
    13. SStudent s2 = { 2, "Ming"}; //C++定义struct变量时,前面的struct也可以不写
    14. cout << s1.nNo << endl;
    15. cout << s1.strName << endl;
    16. cout << s2.nNo << endl;
    17. cout << s2.strName << endl;
    18. return 0;
    19. }

            b.第二种语法表示

            typedef struct 结构体名称{
               数据类型 member1;
               数据类型 member2;
            }结构体名称别名;
           

      这种情况使用typedef关键字,声明了数据类型的别名,所以在定义结构体 变量时有两种方式:
        第一种:结构体名称 构体变量名
        第二种:结构体名称别名 结构体变量名

    1. #include
    2. #include
    3. using namespace std;
    4. typedef struct SStudent
    5. {
    6. int nNo;
    7. std::string strName;
    8. } SStud;
    9. int main(int argc, char *argv[])
    10. {
    11. SStudent s1 = { 1, "ying"}; //使用结构体名称
    12. SStud s2 = { 2, "Ming"}; //使用结构体名称别名
    13. cout << s1.nNo << endl;
    14. cout << s1.strName << endl;
    15. cout << s2.nNo << endl;
    16. cout << s2.strName << endl;
    17. return 0;
    18. }

       c.第三种语法表示

            struct 结构体名称{
               数据类型 member1;
               数据类型 member2;
            }结构体变量;

    1. #include
    2. #include
    3. using namespace std;
    4. struct SStudent
    5. {
    6. int nNo;
    7. std::string strName;
    8. } stu;
    9. int main(int argc, char *argv[])
    10. {
    11. // stu s2; //错误,没有使用typedef关键字,stu是变量不是类型
    12. stu = { 1, "ying"}; //使用初始化表赋值
    13. stu.nNo = 2; //修改成员nNo值
    14. stu.strName = "XiaoMing";//修改成员strName值
    15. cout << stu.nNo << endl;
    16. cout << stu.strName << endl;
    17. return 0;
    18. }

       d.第四种语法表示

       //匿名结构体

            struct {
               数据类型 member1;
               数据类型 member2;
            }结构体变量名;

    在声明的同时定义了结构体变量,但不能在其它地方声明,因为我们无法得知该结构体的标识符,所以就无法通过标识符来声明变量。

    1. #include
    2. #include
    3. using namespace std;
    4. //声明了结构体并定义(且只能在这里定义)了两个该结构体的变量,
    5. //由于无法获取结构体名称(因为匿名),所以无法在其他地方定义该结构体变量
    6. struct
    7. {
    8. int nNo;
    9. std::string strName;
    10. } stu1, stu2;
    11. int main(int argc, char *argv[])
    12. {
    13. stu1 = { 1, "ying"}; //使用初始化表赋值
    14. stu2 = { 2, "Ming"}; //使用初始化表赋值
    15. cout << stu1.nNo << endl;
    16. cout << stu1.strName << endl;
    17. cout << stu2.nNo << endl;
    18. cout << stu2.strName << endl;
    19. return 0;
    20. }

    3、结构体的2种初始化方式

       a. 使用初始化列表

         语法:

             //初始化列表中的项目是按照结构体声明中成员的顺序依次赋值,各个成员的赋值用逗号分隔并用大括号括起来

            结构体类型 变量名 = {member1取值,member2取值,member3取值...};

             前面的例子都使用了初始化列表来初始化,这里不再记录例子。

            几个注意点:

            1)使用初始化列表时可以仅仅初始化部分成员,如果某个成员未被初始化,则所有跟在它后面的成员都需要保留为未初始化。C++未提供跳过某个成员初始化其他成员的方法。

    1. #include
    2. #include
    3. using namespace std;
    4. //声明了结构体,增加nAge成员,并且定义了两个变量stu1和stu2
    5. struct SStudent
    6. {
    7. int nNo;
    8. std::string strName;
    9. int nAge;
    10. } stu1, stu2;
    11. int main(int argc, char *argv[])
    12. {
    13. stu1 = { 1, "ying"}; //合法,仅初始化了nNo和strName,不初始化nAge
    14. // stu2 = { 2, 11}; //非法,不能跳过strName给nAge赋值
    15. cout << stu1.nNo << endl;
    16. cout << stu1.strName << endl;
    17. cout << stu1.nAge << endl;
    18. cout << stu2.nNo << endl;
    19. cout << stu2.strName << endl;
    20. cout << stu2.nAge << endl;
    21. return 0;
    22. }

           2)可以在结构体声明中使用默认值初始化结构体成员

    1. #include
    2. #include
    3. using namespace std;
    4. //声明了结构体,并且定义了两个变量stu1和stu2
    5. struct SStudent
    6. {
    7. int nNo = 1;
    8. std::string strName = "YunCai";
    9. int nAge = 6;
    10. } stu1, stu2;
    11. int main(int argc, char *argv[])
    12. {
    13. stu1 = { 2, "ying"}; //不给nAge赋值,将取值默认值6
    14. cout << stu1.nNo << endl;
    15. cout << stu1.strName << endl;
    16. cout << stu1.nAge << endl;
    17. cout << stu2.nNo << endl; //不给stu2赋值,所有成员都使用默认值
    18. cout << stu2.strName << endl;
    19. cout << stu2.nAge << endl;
    20. return 0;
    21. }

       运行结果:

       b. 使用构造函数

            与类构造函数一样,结构体的构造函数必须是与结构体名称相同的公共成员函数,并且没有返回类型。因为默认情况下,所有结构体成员都是公开的,所以不需要使用关键字 public。

    1. #include
    2. #include
    3. using namespace std;
    4. //声明了结构体,
    5. //并且定义了一个带有三个默认参数的构造函数
    6. //在定义SStudent 变量而不向其传递任何参数时,提供默认值
    7. struct SStudent
    8. {
    9. int m_nNo;
    10. string m_strName;
    11. int m_nAge;
    12. SStudent(int nNo = 1, string strName = "YunCai", int nAge = 6)
    13. {
    14. m_nNo = nNo;
    15. m_strName = strName;
    16. m_nAge = nAge;
    17. }
    18. };
    19. int main(int argc, char *argv[])
    20. {
    21. SStudent stu1; //调用构造函数并且使用默认参数
    22. SStudent stu2(2, "ying"); //调用构造函数并传参nNo = 2, strName = "ying"
    23. cout << stu1.m_nNo << endl;
    24. cout << stu1.m_strName << endl;
    25. cout << stu1.m_nAge << endl;
    26. cout << stu2.m_nNo << endl;
    27. cout << stu2.m_strName << endl;
    28. cout << stu2.m_nAge << endl;
    29. return 0;
    30. }

    4、结构体成员的访问

    结构体数据成员都是public的,所以它们可以被直接访问,并且可以像常规变量一样使用。

    结构体变量使用点运算符.访问数据成员,结构体指针使用->指针运算符访问数据成员。

    1. #include
    2. #include
    3. using namespace std;
    4. struct SStudent
    5. {
    6. int m_nNo;
    7. string m_strName;
    8. int m_nAge;
    9. SStudent(int nNo = 1, string strName = "YunCai", int nAge = 6)
    10. {
    11. m_nNo = nNo;
    12. m_strName = strName;
    13. m_nAge = nAge;
    14. }
    15. };
    16. int main(int argc, char *argv[])
    17. {
    18. SStudent stu1; //调用构造函数并且使用默认参数
    19. SStudent stu2(2, "ying"); //调用构造函数并传参nNo = 2, strName = "ying"
    20. SStudent* stu3 = new SStudent(3, "Ming", 8); //使用new初始化SStudent对象指针
    21. cout << stu1.m_nNo << endl;//使用点运算符访问
    22. cout << stu1.m_strName << endl;
    23. cout << stu1.m_nAge << endl;
    24. cout << stu2.m_nNo << endl;
    25. cout << stu2.m_strName << endl;
    26. cout << stu2.m_nAge << endl;
    27. cout << stu3->m_nNo << endl;//使用指针运算符访问
    28. cout << stu3->m_strName << endl;
    29. cout << stu3->m_nAge << endl;
    30. delete stu3;
    31. stu3 = nullptr;
    32. return 0;
    33. }

    5、结构体的嵌套

    就像一个类的对象可以作为成员放在另一个类中,一个结构体的变量可以作为成员放在另一个结构体中。

    1. #include
    2. #include
    3. using namespace std;
    4. //声明了结构体SDate日期
    5. struct SDate
    6. {
    7. int m_nYear;
    8. int m_nMonth;
    9. int m_nDay;
    10. SDate(const int& nY = 2000, const int& nM = 11, const int& nD = 2)
    11. {
    12. m_nYear = nY;
    13. m_nMonth = nM;
    14. m_nDay = nD;
    15. }
    16. };
    17. //声明了结构体SStudent学生,其中m_dateBirth是学生出生日期
    18. struct SStudent
    19. {
    20. int m_nNo;
    21. string m_strName;
    22. int m_nAge;
    23. SDate m_dateBirth;
    24. SStudent(const int& nNo = 1, const string& strName = "YunCai",
    25. const int& nAge = 6, const SDate& dateBirth= SDate())
    26. {
    27. m_nNo = nNo;
    28. m_strName = strName;
    29. m_nAge = nAge;
    30. m_dateBirth = dateBirth;
    31. }
    32. };
    33. //使用一个函数打印学生信息,参数类型为常量引用SStudent
    34. void print(const SStudent& stu)
    35. {
    36. cout << stu.m_nNo << " " << stu.m_strName << " " << stu.m_nAge << " ";
    37. cout <<"Birthday:" << stu.m_dateBirth.m_nYear << "_" <<
    38. stu.m_dateBirth.m_nMonth << "_" << stu.m_dateBirth.m_nDay << endl;
    39. }
    40. //修改学号增加100,参数类型为值传递,返回值为SStudent
    41. SStudent UpdateNo1(SStudent stu)
    42. {
    43. stu.m_nNo += 100;
    44. return stu;
    45. }
    46. //修改学号增加100,参数类型为引用传递
    47. void UpdateNo2(SStudent& stu)
    48. {
    49. stu.m_nNo += 100;
    50. }
    51. int main(int argc, char *argv[])
    52. {
    53. SStudent stu1; //调用构造函数并且使用默认参数
    54. print(stu1);
    55. stu1 = UpdateNo1(stu1);
    56. print(stu1);
    57. SDate stu2_birthday(1999, 9, 10);
    58. SStudent stu2(2, "Ying", 7, stu2_birthday);//调用够用构造函数并且传了4个参数
    59. print(stu2);
    60. UpdateNo2(stu2);
    61. print(stu2);
    62. return 0;
    63. }

    运行结果:

    6、将结构体作为参数和返回值

      a.将结构体作为参数:与类对象一样,结构体变量也可以通过值、引用和常量引用传递给函数。

            1)   值传递:需要生成整个原始结构的副本并传递给函数。因为不希望浪费时间来复制整个结构体,所以,除非结构很小,否则一般会通过引用将结构体传递给函数。

            2)引用传递:引用传递不会生成原始结构体的副本,函数可以直接访问原始结构体的成员变量,也可能更改它们。

            3)常量引用传递:常量引用传递也不会生成原始结构体的副本,函数直接访问原始结构体的成员变量但不能修改原始结构体的成员变量。

    b.将结构体作为返回值:函数的返回类型是结构体的名称。

    5、结构体的嵌套中的例子,print函数使用了常量引用传递进行传值,UpdateNo1函数的参数类型为值传递,返回值为结构体,UpdateNo2函数的参数类型为引用传递。

    二、C++ class和struct的区别

          结构体和类基本雷同,唯一区别是,类中成员变量默认为私有private,而结构体中则为公有public。因此在使用时,我们可以根据不同的场景或者需求来选择使用struct或者class。

             a.这些情况下使用struct比class更好

                    1)纯数据结构:如果一个类只包含数据成员,而没有成员函数;

                     2)数据成员全部为public;

                    3)用于C接口:如果一个类需要与C语言交互,例如作为C语言库的接口,那么使用struct更加合适(因为C语言不支持类的概念,而使用struct可以更加方便地进行数据传递);

                    4)继承自C结构体:如果一个类需要继承自一个C语言的结构体,那么使用struct更加合适。因为C结构体默认为public,并且在C++中可以使用struct来继承。

            b.这些情况下使用class比struct更好

                    1)需要保证数据的安全性,对数据的访问控制比较严格:使用class可以将数据成员设置为私有成员private,防止外部直接修改数据;

                    2)需要进行多态:如果一个类需要进行多态操作,例如需要使用虚函数,那么使用class更加合适。

    三、C++ struct和 c struct的区别 

            a. C++中定义结构体变量时可以省略struct,但C语言中不可以省略;

            b. C++中struct可以和类一样,有访问权限,并可以定义成员函数; C语言中struct没有访问权限的设置,是一些变量的集合体,不能定义成员函数;

            c.C++中struct可以继承,也可以实现多态;C语言中struct不支持继承和多态;

    四、struct计算结构体某个成员相对于结构体基址的偏移

    如何计算:

               #define offsetof(s,m) (size_t)&(((s *)0)->m)

    解释:

             ((s *)0):强制转化成数据结构指针,并使其指向地址0;
            ((s *)0)->m:使该指针指向成员m
            &(((s *)0)->m):获取该成员m的地址
            (size_t)&(((s *)0)->m):转化这个地址为合适的类型

    使用场景

            offsetof已经被定义在系统库中,所以直接使用offsetof计算结构体某个成员相对于结构体基址的偏移

    例子:

            要计算如下SDate中m_nDay成员相对于结构体基址的偏移,可以使用 offsetof(SDate, m_nDay)。

            struct SDate{
                    int m_nYear;
                    int m_nMonth;
                    int m_nDay;
            };



    参考资料如下:

    1、C++ struct的4种定义方式_c++ struct 定义_Mr顺的博客-CSDN博客

    2、C++结构体完全攻略(超详细) 

    3、什么时候以struct 替代class? - 知乎

  • 相关阅读:
    类与对象(八)----重载OverLoad
    基于FPGA的数字滤波器fir
    数字签名与数字信封
    VB、C#、VC使用条件编译自动选择结构体对齐方式
    qiankun-boot 一个开箱即用的 qiankun cli
    蜣螂优化(DBO)算法的5种最新变体(含MATLAB代码)
    Linux - 进程管理
    OLED显示文字,字母,数字
    数据结构-浅入浅出
    【WEEK15】 【DAY2】【DAY3】邮件任务【中文版】
  • 原文地址:https://blog.csdn.net/Levon123/article/details/132597205