C++语言继承了C语言的struct,并且加以扩充。在C语言中struct是只能定义数据成员,而不能定义成员函数的。而在C++中,struct类似于class,在其中既可以定义数据成员,又可以定义成员函数。

结构类型是用户定义的复合类型,它可由不同类型的字段或成员构成。在C++中,struct与class基本是通用的,唯一不同的是如果使用class关键字,类中定义的成员变量或成员函数默认都是private属性的,而采用struct关键字,结构体中定义的成员变量或成员函数默认都是public属性的。

在C中,必须显示使用struct关键字来声明结构。在C++中,不需要在定义该类型之后使用struct关键字。可以选择在定义结构类型时,通过在右大括号和分号之间放置一个或多个逗号分隔的变量名称来声明变量。可以初始化结构变量,每个变量的初始化必须括在大括号中。

Differences between C struct & C++ struct:

(1)、 C structure can't contain functions means only data members are allowed, but structure in C++ can have both functions &  data members.

(2)、 struct keyword is necessary in C to create structure type variable, but it is  redundant & not necessary in C++.

(3)、 Size of empty structure is undefined behavior in C, but it is always 1 in C++.

(4)、 Structure in C can't have static members, but C++ structure can have static members.

(5)、 Structure members can't be directly initialized inside the struct in C, but it is allowed in C++ since C++11.

(6)、 We can have both pointers and references to struct in C++, but only pointers to structs are allowed. (References aren't feature of C language).

(7)、 C++ also have .* and -> operators to access individual members of struct, but C doesn't have such kind of operators.

(8)、 struct declaration establishes a  scope in C++ and not in C, which makes member enumerators and nested structs possible in C++(you can *write* them inside a struct in C, but they escape and become local to whatever function the parent struct is in).

(9)、 In C, we need to use struct tag whenever we declare a struct variable. In C++, the struct tag is not necessary.

(10)、C++ structures are very similar to a class, with the only difference being that in a class, all members are private by default. But in a C++ structure, all members are public by default. In C, there is no concept of public or private.

(11)、C++ structures can have member functions, whereas C structures cannot.

(12)、You can have constructors, destructors, copy constructors and so on in C++ structures. You cannot in C structures.

(13)、C++ structures can have static members, whereas C structures cannot.

下面是从其他文章中copy的测试代码,详细内容介绍可以参考对应的reference:

#include "struct.hpp"
#include <cstring>
#include <cstdlib>
#include <iostream>///
// reference: https://msdn.microsoft.com/zh-cn/library/64973255.aspx
struct PERSON {   // Declare PERSON struct typeint age;   // Declare member typeslong ss;float weight;char name[25];
} family_member;   // Define object of type PERSONstruct CELL {   // Declare CELL bit fieldunsigned short character : 8;  // 00000000 ????????unsigned short foreground : 3;  // 00000??? 00000000unsigned short intensity : 1;  // 0000?000 00000000unsigned short background : 3;  // 0???0000 00000000unsigned short blink : 1;  // ?0000000 00000000
} screen[25][80];       // Array of bit fields int test_struct1()
{struct PERSON sister;   // C style structure declarationPERSON brother;   // C++ style structure declarationsister.age = 13;   // assign values to membersbrother.age = 7;std::cout << "sister.age = " << sister.age << '\n';std::cout << "brother.age = " << brother.age << '\n';CELL my_cell;my_cell.character = 1;std::cout << "my_cell.character = " << my_cell.character<<'\n';return 0;
}//
// reference: http://www.tutorialspoint.com/cplusplus/cpp_data_structures.htm
struct Books {char  title[50];char  author[50];char  subject[100];int   book_id;
};void printBook(struct Books book)
{std::cout << "Book title : " << book.title << std::endl;std::cout << "Book author : " << book.author << std::endl;std::cout << "Book subject : " << book.subject << std::endl;std::cout << "Book id : " << book.book_id << std::endl;
}int test_struct2()
{struct Books Book1;        // Declare Book1 of type Bookstruct Books Book2;        // Declare Book2 of type Book// book 1 specificationstrcpy(Book1.title, "Learn C++ Programming");strcpy(Book1.author, "Chand Miyan");strcpy(Book1.subject, "C++ Programming");Book1.book_id = 6495407;// book 2 specificationstrcpy(Book2.title, "Telecom Billing");strcpy(Book2.author, "Yakit Singha");strcpy(Book2.subject, "Telecom");Book2.book_id = 6495700;// Print Book1 infoprintBook(Book1);// Print Book2 infoprintBook(Book2);return 0;
}///
// reference: http://www.dummies.com/how-to/content/how-to-build-a-structure-template-in-c.html
template<typename T>
struct Volume {T height;T width;T length;Volume(){height = 0;width = 0;length = 0;}T getvolume(){return height * width * length;}T getvolume(T H, T W, T L){height = H;width = W;length = L;return height * width * length;}
};int test_struct3()
{Volume<int> first;std::cout << "First volume: " << first.getvolume() << std::endl;first.height = 2;first.width = 3;first.length = 4;std::cout << "First volume: " << first.getvolume() << std::endl;Volume<double> second;std::cout << "Second volume: " << second.getvolume(2.1, 3.2, 4.3) << std::endl;std::cout << "Height: " << second.height << std::endl;std::cout << "Width: " << second.width << std::endl;std::cout << "Length: " << second.length << std::endl;return 0;
}///
// reference: http://www.java2s.com/Code/Cpp/Class/Constructoranddestructorinsideastruct.htm
struct StringClass
{StringClass(char *ptr);~StringClass();void show();
private:char *p;int len;
};StringClass::StringClass(char *ptr)
{len = strlen(ptr);p = (char *)malloc(len + 1);if (!p) {std::cout << "Allocation error\n";exit(1);}strcpy(p, ptr);
}StringClass::~StringClass()
{std::cout << "Freeing p\n";free(p);
}void StringClass::show()
{std::cout << p << " - length: " << len;std::cout << std::endl;
}int test_struct4()
{StringClass stringObject1("www.java2s_1.com."), stringObject2("www.java2s_2.com.");stringObject1.show();stringObject2.show();return 0;
}

GitHub:  https://github.com/fengbingchun/Messy_Test

C++中struct的使用相关推荐

  1. C#中struct和class的使用区别是什么?

    class是引用类型,struct是值类型 引用类型在堆上,值类型是内联的. 值类型有全部的值的内容,而引用类型只有一个地址. 值类型总是有一个值,而引用类型指针可以为空. 为了优化减少体积 需要传递 ...

  2. golang中struct字段

    golang中struct字段名首字母必须大写,不然json无法解析 golang中struct字段后面json字段要小写或小写加下划线 golang中首字母大写表示共有

  3. 关于readdir返回值中struct dirent.d_type的取值有关问题(转)

    关于readdir返回值中struct dirent.d_type的取值问题 原网页链接 http://www.gnu.org/software/libc/manual/html_node/Direc ...

  4. C++中struct和class关键字的区别

    文章目录 1 C++中struct和class关键字的区别 1.1 类的关键字 1 C++中struct和class关键字的区别 1.1 类的关键字 C++中类的关键字: struct在C语言中已经有 ...

  5. C与C++中struct及C++中struct与class的区别

    C++中struct与class的区别 struct class 备注 成员函数 能 能 均有构造函数及析构函数 继承性 能 能 多态性 能 能 均有虚函数 默认成员属性 public private ...

  6. C++中Struct和Class的区别

    Struct和Class的区别 今天这篇博文主要讲解在C++中关键字struct和class的区别.这篇博文,将会系统的将这两个关键字的不同面进行详细的讲解. 从语法上来讲,class和struct做 ...

  7. C#中struct和class的区别详解

    本文详细分析了C#中struct和class的区别,对于C#初学者来说是有必要加以了解并掌握的. 简单来说,struct是值类型,创建一个struct类型的实例被分配在栈上.class是引用类型,创建 ...

  8. C# 中 Struct 与 Class 的区别,以及两者的适用场合

    C# 中 Struct 与 Class 的区别,以及两者的适用场合 先说区别,原文出处 http://www.dotnetspider.com/resources/740-Difference-bet ...

  9. C中struct的函数的实现

    C中struct的函数实现,只能用函数指针成员. C结构体内不能有函数的代码,但可以有函数的指针. C/C code Code highlighting produced by Actipro Cod ...

  10. matlab中struct2,Matlab中struct的用法

    struct在matlab中是用来建立结构体数组的.通常有两种用法: s = struct('field1',{},'field2',{},...) 这是建立一个空的结构体,field1,field2 ...

最新文章

  1. TensorFlow之会话
  2. 油气储运工程中计算机的应用,中国石油大学(北京) 油气储运工程专业介绍
  3. 鸟哥的Linux私房菜(基础篇)-第二章、 Linux 如何学习(二.3. 有心朝Linux作业系统学习者的学习态度)
  4. Bash中的whereis
  5. Image.FromStream与Image.FromFile
  6. docker小实战和应用
  7. 【POJ - 1182】 食物链(附超详细讲解)(并查集--种类并查集经典题)
  8. 面试官重点考察求职者这5项能力
  9. redis——哈希(hash)
  10. ViewPager PagerAdapter未更新视图
  11. 用友NC63 医药行业 消耗汇总 出库单批次模糊查询
  12. tf卡工具android,SD/TF卡专用格式化工具
  13. 谷歌浏览器设置免跨域 Mac
  14. PS实用小技巧--修改图片上的文字
  15. 项目管理高手常用的10种图表!
  16. python中stripped string_22-.strings 和 stripped_strings变量多个文本
  17. 【C语言】sizeof操作符详解
  18. Android设备硬件序列号(SN、串号)分析
  19. ChinaSoft 论坛巡礼 | 泛在计算时代的智能化运维
  20. 微信小程序传参到后端解析出手机号(java实现)

热门文章

  1. 70种芯片细分领域、国产MCU重要代表企业
  2. 力扣(LeetCode)刷题,简单题(第7期)
  3. 基于onnx的人脸识别
  4. Win10 + QT5.14.2 + Opencv4.1.1 编译环境搭建
  5. java利用递归画杨辉三角_用java程序编写杨辉三角形,初学者适用
  6. 一、网页端文件流的传输
  7. ehchache验证缓存过期的api_ASP.NET Core ResponseCache进行缓存操作
  8. 基于平面几何精确且鲁棒的尺度恢复单目视觉里程计
  9. BST(binary search tree)类型题目需要用到的头文件binary_tree.h
  10. 继承和多态 2.0 -- 继承的六个默认成员函数