[Turning]struct usage in-depth exploration

Source: Internet
Author: User

Http://www.cnblogs.com/hnrainll/archive/2010/02/23/1671967.html

Deep Exploration of struct usage
Author: cloudward

1. The great role of structs
In the face of a person's large-C + + program, only look at its use of the struct, we can evaluate the programming experience of its authors. Because of a large, C + + program, it is bound to involve some (or even large) combinations of data, which can combine data that is meant to belong to a whole. To some extent, will not use a struct, how to use a struct is to distinguish whether a developer has a rich development experience of the logo.

In the network protocol, the communication control, the embedded system C/s programming, we often want to transmit is not a simple byte stream (char array), but a variety of data combination of a whole, its representation is a structure. Inexperienced developers tend to store all the content that needs to be transferred sequentially in a char array, using pointer offsets to transmit information such as network messages.  This makes programming complex, error-prone, and once the control mode and communication protocol changes, the program will be very carefully modified. An experienced developer has the flexibility to use the structure, for example, assuming that the network or control protocol requires the transmission of three messages in the form Packeta, PACKETB, Packetc:struct structa
{
int A;
Char b;
};struct STRUCTB
{
Char A;
Short B;
};struct STRUCTC
{
int A;
Char b;
float C;
Excellent program designers design the transmitted message: struct Commupacket
{
int ipackettype; Message type flag
Union//Each transmission is one of three messages, using the Union
{
struct STRUCTA Packeta;
struct STRUCTB Packetb;
struct STRUCTC packetc;
}
};  In the transmission of the message, the direct transfer of the struct commupacket a whole. Suppose the prototype of the sending function is as follows://Psenddata: Send the first address of the byte stream, Ilen: the length to send
Send (char * psenddata, unsigned int ilen);
The sender can send an instance of the struct commupacket directly to the following call Sendcommupacket:
Send (char *) &sendcommupacket, sizeof (Commupacket));
Assume the prototype of the receive function is as follows:
Precvdata: Send the first address of the byte stream, Ilen: the length to receive
Return value: The number of bytes actually received
unsigned int Recv (char * precvdata, unsigned int ilen), the receiver can directly make the following call to save the received data in an instance commupacket of struct Recvcommupacket:  RECV (char *) &recvcommupacket, sizeof (Commupacket)); Then determine the message type to be processed accordingly: switch (recvcommupacket. Ipackettype)
{
Case PACKET_A:
//A-Class Message processing
Break
Case PACKET_B:
//b-Class Message processing
Break
Case Packet_c:
//C-Class Message processing
Break
The most notable of the above programs is send (char *) &sendcommupacket, sizeof (Commupacket));
RECV (char *) &recvcommupacket, sizeof (Commupacket));  Forced type conversion in: (char *) &sendcommupacket, (char *) &recvcommupacket, take address first, and then convert to char pointer, so you can directly take advantage of the function of the byte stream processing. With this coercion type conversion, we can also facilitate the programming of the program, for example, to initialize the memory of Sendcommupacket to 0, you can call the standard library function memset (): memset ((char *) &sendcommupacket,0, sizeof (Commupacket)); 2. Aligning members of a struct
Intel, Microsoft and other companies have been a similar interview question: 1. #include <iostream.h>2. #pragma pack (8)
3. struct EXAMPLE1
4. {
5. Short A;
6. Long B;
7.};8. struct EXAMPLE2
9. {
. Char C;
One. Example1 Struct1;
Short E;
13.};
#pragma pack () 15. int main (int argc, char* argv[])
16. {
Example2 struct2;18. cout << sizeof (example1) << Endl;
cout << sizeof (example2) << Endl;
cout << (unsigned int) (&AMP;STRUCT2.STRUCT1)-(unsigned int) (&AMP;STRUCT2)
<< endl;21. return 0;
22. What is the input result of the Q program? The answer is: 8
16
4 Don't understand? Still don't understand? Here are one by one ways: 2.1 The natural-to-bounded struct is a composite data type whose constituent elements can be variables of basic data types (such as int, long, float, etc.) or data units of some composite data types (such as array, struct, union, and so on). For structs, the compiler automatically aligns member variables to improve computational efficiency. By default, the compiler allocates space for each member of the struct according to its natural bounded (natural alignment) condition.  Each member is stored sequentially in memory in the order in which they are declared, and the address of the first member is the same as the address of the entire structure.  The natural-to-bounds (natural alignment) is the default alignment, which is aligned by the largest member of the size in the struct. Example: struct naturalalign
{
Char A;
Short B;
char c;
}; In the above structure, the size of the largest is short, its length is 2 bytes, so the structure of Char members A, c are aligned in 2 units, sizeof (naturalalign) result is equal to 6; if instead: struct naturalalign
{
Char A;
int b;
char c;
}; The result is obviously 12. 2.2 Specifies the bounds of the boundary, you can change the default boundary condition by the following method: · Using the pseudo-directive #pragma pack (n), the compiler will align N bytes;
·  Use pseudo-Directives #pragma pack () to cancel custom byte alignment.  Note: If the n specified in #pragma pack (n) is greater than the size of the largest member in the struct, it does not work, and the struct is still bounded by the largest member of size. Example: #pragma pack (n)
struct naturalalign
{
Char A;
int b;
char c;
};
#pragma pack () when n is 4, 8, 16 o'clock, the alignment is the same, and sizeof (naturalalign) results are equal to 12.  And when n is 2 o'clock, it plays a role, making sizeof (naturalalign) a result of 8. In the VC + + 6.0 compiler, we can specify its bounds (see Figure 1), which is done by selecting the PROJETCT > Setting > C + + menu, and specifying the way you want the bounds in the struct member alignment. Figure 1: Specifying the bounded mode in VC + + 6.0 In addition, by __attribute ((aligned (n)), the members of the struct can be aligned to the N-byte boundary, but it is less used and therefore not explained in detail.  The answers to the 2.3-sided questions are now available in a comprehensive solution to Intel and Microsoft's face questions. The 2nd line of #pragma pack (8) in the program specifies a bounds of 8, but because the member of Struct example1 has a maximum size of 4 (long variable size 4), the struct example1 is still in the 4 byte bounds, the struct The size of the example1 is 8, which is the output of line 18th, and the struct example2 contains the struct example1, which itself contains a maximum size of 2 for a simple data member (short variable e), but because it contains a struct Example1, while the largest member of the struct example1 size is 4,struct example2 should also be 4 bound, and the bounds specified in the #pragma pack (8) to struct example2 also do not work, Therefore, the output of 19 rows is 16; Since the members of struct example2 are in the bounds of 4, the char variable C should be supplemented with 3 empty, followed by the member Struct1 memory space, and 20 rows output 4. 3. Deep differences between C and C + + structs
In the C + + language, a struct has the function of "class", which differs from the keyword class in that the default access rights for member variables and functions in a struct are public, while class is private. For example, define struct classes and class classes: struct STRUCTA
{
Char A;
...
}
Class ClassB
{
Char A;
...
}: struct A;
A.A = ' a '; Access public members, legal
ClassB b;
B.A = ' a '; Access to private members, not legal many of the literature wrote here that the whole difference between struct and class is given in C + +, but it is another point to note that the struct in C + + maintains full compatibility with C's struct (which conforms to C + + 's original intent- -"A better C"), thus, the following operation is legal://define Struct
struct STRUCTA
{
Char A;
Char b;
int C;
};
Structa a = {' A ', ' a ', 1}; When defining the initial value directly, the struct can assign the initial value of its member variable directly to {} at the time of definition, while class cannot, in the classic bibliography "Thinking C + + 2nd Edition", the author emphasizes this point. 4. struct Programming considerations
Look at the following program: 1. #include <iostream.h>2. struct STRUCTA
3. {
4. int imember;
5. Char *cmember;
6.};7. int main (int argc, char* argv[])
8. {
9. Structa Instant1,instant2;
10.char C = ' a ';

Instant1.imember = 1;
Instant1.cmember = &c;

13.instant2 = Instant1;

14.cout << * (instant1.cmember) << Endl;

15.* (Instant2.cmember) = ' B ';

cout << * (instant1.cmember) << Endl;

. return 0;
The output of the 14 row is: a
The output of 16 rows is: B Why? The changes we made to the Instant2 in line 15 changed the values of the members in the Instant1!  The reason is that the 13-row Instant2 = Instant1 Assignment statement takes a variable-by-copy, which causes cmember in Instant1 and Instant2 to point to the same piece of memory, so the Instant2 modification is also a modification to instant1.  In C, when a pointer member exists in a struct, it is important to note whether a pointer-type member in 2 instances points to the same piece of memory when the assignment statement is taken. In the C + + language, when a pointer member exists in a struct, we need to rewrite the copy constructor of the struct and make the "=" operator overload. Category: Programming | Permanent link | Comments: 0 | References: 0 | Views: 732
Comparison of struct and class
[2005-11-02 13:13:55 | Author: Cloudward]
C # one. Example comparison of classes and structs: struct example: public struct person
{
String Name;
int height;
int weightc# one. Example comparison of classes and structs: struct example: public struct person
{
String Name;
int height;
int weight
public bool Overweight ()
{
Implement something
}
} Class Example:
public class Testtime
{
int hours;
int minutes;
int seconds;
public void Passtime ()
{
Implementation of behavior
}
} Call Procedure:
public class Test
{
public static Ovid Main
{
Person Myperson=new person//Declaration structure
Testtime mytime=new testtime//Declaration class
}
As we can see from the above example, the declaration of a class is very similar to that of a struct, except that the qualifier is followed by a struct or class, and when used, it is very similar to defining a new structure and defining a new class. So what is the specific difference between a class and a struct? Two. Class-to-structure differences 1. Value types and reference type structures are value types: value types are assigned addresses on the stack, all base types are struct types, for example: int corresponds to SYSTEM.INT32 structure, string corresponds to System.String structure, By using structs, you can create more value-type classes that are reference types: a reference type that allocates an address stack on a heap is more efficient than a heap, but the stack has limited resources and is not suitable for dealing with large logical complex objects. So structure processing is a small object treated as a base type, whereas a class handles a business logic because structs are value types, assignments between structs can create new structures, and classes are reference types. The assignment between classes is just a copy of the reference note: 1. Although structs are not the same as classes, their base types are objects (object), and the base types of all types in C # are all 2. Although the initialization of the structure also uses the new operator, the structure object is still allocated on the stack instead of on the heap. If you do not use new, the field remains unassigned until all fields are initialized, and the object is not available 2. Inheritance structure: Can not inherit from another structure or class, itself can not be inherited, although the structure is not explicitly declared with sealed, but the structure is implicit sealed.
Class: Fully extensible, unless the declared declaration sealed otherwise the class can inherit other classes and interfaces, and itself can be inherited note: Although structs cannot be inherited, structs can inherit interfaces, like methods and classes that inherit interfaces such as: structs implement interfaces

Interface IImage
{
void Paint ();
}

struct Picture:iimage
{
public void Paint ()
{
Painting Code goes here
}
private int x, y, Z; Other structs Members
} 3. Internal structure: Structure: There is no default constructor, but you can add constructors without destructors without the abstract and sealed (because they cannot be inherited) cannot have protected modifiers can not use the new initialization in the struct to initialize the instance field is the wrong class : There are default constructors that have destructors that can use abstract and sealed have protected modifiers that must be initialized with new three. How to choose a struct or a class after discussing the similarities and differences between a struct and a class, the following discusses how to choose whether to use structs or classes: 1. Stack space is limited, and for a large number of logical objects, creating a class is 2 better than creating a struct. Structures represent lightweight objects such as points, rectangles, and colors, for example, if you declare an array that contains 1000 point objects, additional memory is allocated for each object that is referenced. In this case, the cost of the structure is lower. 3. Classes are the best choice for 4 when performing abstract and multi-level object hierarchies.  Most of the time, when the type is just some data, the best choice for structure is C + + in the C + + language, the struct has the function of "class", which differs from the keyword class in that the default access rights for member variables and functions in a struct are public, while class is private. For example, define struct classes and class classes: struct STRUCTA
{
Char A;
...
}
Class ClassB
{
Char A;
...
}: struct A;
A.A = ' a '; Access public members, legal
ClassB b;
B.A = ' a '; Access to private members, not legal many of the literature wrote here that the whole difference between struct and class is given in C + +, but it is another point to note that the struct in C + + maintains full compatibility with C's struct (which conforms to C + + 's original intent- -"A better C"), thus, the following operation is legal://define Struct
struct STRUCTA
{
Char A;
Char b;
int C;
};
Structa a = {' A ', ' a ', 1}; When defining the initial value directly, the struct can assign the initial value of its member variable directly to {} at the time of definition, while class cannot, in the classic bibliography "Thinking C + + 2nd Edition", the author emphasizes this point.

[Turning]struct usage in-depth exploration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.