C++中struct的使用

时间:2023-01-29 19:50:15

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

相关文章