C++中struct的使用

2023-05-16

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 type
	int age;   // Declare member types
	long ss;
	float weight;
	char name[25];
} family_member;   // Define object of type PERSON

struct CELL {   // Declare CELL bit field
	unsigned short character : 8;  // 00000000 ????????
	unsigned short foreground : 3;  // 00000??? 00000000
	unsigned short intensity : 1;  // 0000?000 00000000
	unsigned short background : 3;  // 0???0000 00000000
	unsigned short blink : 1;  // ?0000000 00000000
} screen[25][80];       // Array of bit fields 

int test_struct1()
{
	struct PERSON sister;   // C style structure declaration
	PERSON brother;   // C++ style structure declaration
	sister.age = 13;   // assign values to members
	brother.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 Book
	struct Books Book2;        // Declare Book2 of type Book

	// book 1 specification
	strcpy(Book1.title, "Learn C++ Programming");
	strcpy(Book1.author, "Chand Miyan");
	strcpy(Book1.subject, "C++ Programming");
	Book1.book_id = 6495407;

	// book 2 specification
	strcpy(Book2.title, "Telecom Billing");
	strcpy(Book2.author, "Yakit Singha");
	strcpy(Book2.subject, "Telecom");
	Book2.book_id = 6495700;

	// Print Book1 info
	printBook(Book1);

	// Print Book2 info
	printBook(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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++中struct的使用 的相关文章

  • 为什么结构中“[0]byte”的位置很重要?

    0 byte在golang中不应该占用任何内存空间 但这两个结构体的大小不同 type bar2 struct A int 0 byte type bar3 struct 0 byte A int 那么为什么这个位置 0 byte这里重要吗
  • Swift:协议、结构、类

    我开始学习 Swift 语言 但在理解协议 结构和类方面遇到了困难 我来自 Android 方面的编程 所以我相信 Swift 协议基本上是 Java 接口 其中每一个的正确用例是什么 这些类比并不 完全 正确 但这就是我所理解的要点 是的
  • C 中使用指针的结构冒泡排序

    我想使用 C 中的冒泡排序算法和指针对结构数组进行排序 我有一个汽车结构 typedef struct char model 30 int hp int price cars 我为 12 个项目分配内存 cars pointer cars
  • Python:结构体和数组与 ctypes 中的类似功能

    Python 提供了以下三个处理 C 类型以及如何处理它们的模块 struct https docs python org 3 library struct html对于 C 结构体 array https docs python org
  • 在 Go 中,如何将结构体转换为字节数组?

    我有一个我定义的结构实例 我想将其转换为字节数组 我尝试了 byte my struct 但这不起作用 另外 我还被指出二进制包 http golang org pkg encoding binary 但我不确定我应该使用哪个函数以及应该如
  • C 中是否可以动态定义结构体

    我很确定这最终将成为一个非常明显的问题 这就是为什么我没有找到太多关于它的信息 不过 我认为还是值得问一下 基本上 使用结构访问数据非常快 如果数据以一种可以立即作为结构进行处理的形式从网络中出来 那么从性能的角度来看 这是非常好的 但是
  • 如何在 Julia 中引用结构本身

    我有这个代码 struct MyStruct text String function MyStruct text String text text do other things end end 当我写这篇文章时 我意识到朱莉娅没有认识到
  • 返回具有关联类型的特征

    struct A struct PropA struct B struct PropB trait AB type prop fn a self gt fn b self p Self prop gt impl AB for A type
  • std::bind2nd 和 std::bind 与二维数组和结构数组

    我知道 C 有 lambda 并且 std bind1st std bind2nd 和 std bind 已弃用 然而 从C 的基础开始 我们可以更好地理解新特性 所以 我从这个非常简单的代码开始 使用int 数组s 第一个例子 与std
  • 对嵌套结构使用自定义解组时,GoLang 结构无法正确解组

    我们需要对嵌套在多个其他结构中的结构使用自定义解组器 而这些结构不需要自定义解组器 我们有很多类似的结构B下面定义的结构 类似于嵌套A 代码的输出是true false 0 预期的true false 2 有任何想法吗 Go 游乐场示例he
  • 解压以 ASCIIZ 字符串结尾的结构

    我正在尝试使用struct unpack 分解以 ASCII 字符串结尾的数据记录 该记录 恰好是 TomTom ov2 记录 具有以下格式 存储为小端 1 byte 4 字节 int 表示总记录大小 包括该字段 4字节整数 4字节整数 可
  • 从其对象获取结构体字段的名称和类型

    例如 我有一个类似这样的结构 struct Test int i float f char ch 10 我有一个该结构的对象 例如 Test obj 现在 我想以编程方式获取字段名称和类型obj 是否可以 顺便说一句 这是 C 你正在要求C
  • Clock_t、time_t 和 struct tm 之间有什么区别?

    Clock t time t 和 struct tm 之间有什么区别 结构体看起来像这样 struct tm int tm sec int tm min int tm hour int tm mday int tm mon int tm y
  • 为什么 C++ 不允许匿名结构?

    某些 C 编译器允许匿名联合和结构作为标准 C 的扩展 这是一些语法糖 偶尔会很有帮助 阻止其成为标准一部分的理由是什么 有技术障碍吗 哲学的 或者只是没有足够的需要来证明它的合理性 这是我正在谈论的内容的示例 struct vector3
  • 易失性结构=结构不可能,为什么?

    struct FOO int a int b int c volatile struct FOO foo int main void foo a 10 foo b 10 foo c 10 struct FOO test foo return
  • 优化 golang 中的数据结构/字对齐填充

    与我在 C 中学到的类似 我相信填充导致了两个结构体实例大小的差异 type Foo struct w byte 1 byte x byte 1 byte y uint64 8 bytes type Bar struct x byte 1
  • 在 C++ 中一般将“可选”字段封装在结构中的最佳方法?

    我有很多具体结构 我想将字段指定为可选 存在或不存在 只是想知道人们有什么想法来实现这一目标 这是一个示例结构 字段也可以是其他结构 甚至是结构的向量 struct LogonMessage t Header t header this p
  • 将 struct* 从 C# 传递到 C++ dll

    C dll中的结构体定义如下 struct WAVE INFO int channel num int audio type char wave data int wave length 调用方法如下 extern C STRUCTDLL
  • 查找c中结构元素的偏移量

    struct a struct b int i float j x struct c int k float l y z 谁能解释一下如何找到偏移量int k这样我们就可以找到地址int i Use offsetof 找到从开始处的偏移量z
  • 根据值匹配数组

    我使用以下代码来解析 yaml 并应得到输出为runners对象和函数build应更改数据结构并根据以下结构提供输出 type Exec struct NameVal string Executer string 这是我尝试过的 但我不知道

随机推荐

  • 代码覆盖率工具OpenCppCoverage在Windows上的使用

    OpenCppCoverage是用在Windows C 43 43 上的开源的代码覆盖率工具 xff0c 源码地址为https github com OpenCppCoverage OpenCppCoverage xff0c 最新发布版本为
  • nerfstudio介绍及在windows上的配置、使用

    nerfstudio提供了一个简单的API xff0c 可以简化创建 训练和可视化NeRF的端到端过程 该库通过模块化每个组件来支持可解释的NeRF实现 nerfstudio源码地址 https github com nerfstudio
  • Qt中QDebug的使用

    QDebug类为调试信息 debugging information 提供输出流 它的声明在 lt QDebug gt 中 xff0c 实现在Core模块中 将调试或跟踪信息 debugging or tracing information
  • OkHttpUtil

    package com example someutil util import com google gson Gson import java util Iterator import java util Map import java
  • Sourcetree介绍及使用

    Sourcetree是一个操作简单但功能强大的免费Git客户端管理工具 xff0c 可应用在Windows和Mac平台 Sourcetree的安装 xff1a 1 从Sourcetree Free Git GUI for Mac and W
  • C++14中lambda表达式新增加的features的使用

    lambda表达式是在C 43 43 11中引入的 xff0c 它们可以嵌套在其它函数甚至函数调用语句中 xff0c C 43 43 11中lambda表达式的使用参考 xff1a https blog csdn net fengbingc
  • OpenSSL简介及在Windows、Linux、Mac系统上的编译步骤

    OpenSSL介绍 xff1a OpenSSL是一个强大的安全套接字层密码库 xff0c 囊括主要的密码算法 常用的密钥和证书封装管理功能及SSL协议 xff0c 并提供丰富的应用程序供测试或其它目的使用 SSL是SecureSockets
  • 信息安全领域相关术语介绍

    一 SSL 安全套接字层 SSL Secure Sockets Layer 是一种协议 xff0c 支持服务通过网络进行通信而不损害安全性 它在客户端和服务器之间创建一个安全连接 然后通过该连接安全地发送任意数据量 SSL最初是用来保障数据
  • 对称加密算法之DES介绍

    DES Data Encryption Standard 是分组对称密码算法 DES采用了64位的分组长度和56位的密钥长度 xff0c 它将64位的输入经过一系列变换得到64位的输出 解密则使用了相同的步骤和相同的密钥 DES的密钥长度为
  • OpenSSL中对称加密算法DES常用函数使用举例

    主要包括3个文件 xff1a 1 cryptotest h ifndef CRYPTOTEST H define CRYPTOTEST H include lt string gt using namespace std typedef e
  • 对称加密算法之RC4介绍及OpenSSL中RC4常用函数使用举例

    RC4是一种对称密码算法 xff0c 它属于对称密码算法中的序列密码 streamcipher 也称为流密码 xff0c 它是可变密钥长度 xff0c 面向字节操作的流密码 RC4是流密码streamcipher中的一种 xff0c 为序列
  • 摘要算法之MD5介绍及OpenSSL中MD5常用函数使用举例

    MD5 Message DigestAlgorithm 5 是计算机中广泛使用的杂凑算法之一 主要可以实现将数据运算后转换为一串固定值 xff0c 其前身主要有MD2 MD3和MD4算法 MD2算法在1989年由Rivest设计开发 xff
  • 非对称加密算法之RSA介绍及OpenSSL中RSA常用函数使用举例

    RSA算法 xff0c 在1977年由Ron Rivest Adi Shamirh和LenAdleman xff0c 在美国的麻省理工学院开发完成 这个算法的名字 xff0c 来源于三位开发者的名字 RSA已经成为公钥数据加密标准 RSA属
  • 有效的rtsp流媒体测试地址汇总

    以下是从网上搜集的一些有效的rtsp流媒体测试地址 xff1a 1 rtsp 218 204 223 237 554 live 1 0547424F573B085C gsfp90ef4k0a6iap sdp 2 rtsp 218 204 2
  • Flask【第十章】:特殊装饰器 @app.before_request 和 @app.after_request 以及@app.errorhandler...

    特殊装饰器 64 app before request 和 64 app after request以及 64 app errorhandler 一 背景 xff1a Flask我们已经学习很多基础知识了 现在有一个问题 我们现在有一个 F
  • Linux Socket基础介绍

    Linux Socket函数库是从Berkeley大学开发的BSD UNIX系统中移植过来的 BSD Socket接口是众多Unix系统中被广泛支持的TCP IP通信接口 xff0c Linux下的Socket程序设计 xff0c 除了微小
  • libcurl库的使用(通过libcurl库下载url图像)

    1 从http curl haxx se download html下载libcurl源码 xff0c 解压缩 xff1b 2 通过CMake cmake gui 生成vs2013 x64位 CURL sln xff1b 3 打开CURL
  • 人工神经网络简介

    本文主要对人工神经网络基础进行了描述 xff0c 主要包括人工神经网络的概念 发展 特点 结构 模型 本文是个科普文 xff0c 来自网络资料的整理 一 人工神经网络的概念 人工神经网络 xff08 Artificial Neural Ne
  • 卷积神经网络(CNN)基础介绍

    本文是对卷积神经网络的基础进行介绍 xff0c 主要内容包括卷积神经网络概念 卷积神经网络结构 卷积神经网络求解 卷积神经网络LeNet 5结构分析 卷积神经网络注意事项 一 卷积神经网络概念 上世纪60年代 xff0c Hubel等人通过
  • C++中struct的使用

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