简体   繁体   中英

Making sense of non-primitive data types

Understanding how primitive data types works is easy: Everything in a computer is stored as a series of 0s and 1s, and so everything I need to store needs to be encoded as a series of 0s and 1s. For example: the real number 3.14 must be stored as a bit pattern, the negative number -1234 must be stored as a bit pattern, the character 'A' must be stored as a bit pattern, etc. When I store one of these data in memory, I have to mark the memory location of where they're stored with a specific data type (eg float for a bit pattern that represents a real number), this data type tells me how to interpret this bit pattern when I ask for it later.

But how this definition applies to something like a class, I mean when I create an object of a specific class, for example:

MyClass mc;

mc does not store a bit pattern that needs to be interpreted in a specific way, how to make sense of considering a class to be a data type? Or is there's another definition for a data type?

A class or struct is a composition of other data types - a composite data type - where the constituent data types may be either primitive or composite data types.

In the following example scenario, X and Y are two composite data types. Y is defined only in terms of primitive data types. X is defined in terms of primitive data types and Y .

struct Y
{
    double* d;
    char e;
}

struct X
{
    float a;
    int b;
    Y c;
}

The compiler decides how it is going to define the bit patterns for X and Y . For example, Y might look like this:

<8 bytes for double* d><1 byte for char e>

And X might look like this:

<4 bytes for float a><4 bytes for int b><9 bytes for Y c>

The particular bit pattern the compiler chooses for each class or struct is not important to know for understanding the concept. What's important is that the compiler picks a particular bit pattern for each class or struct and then consistently uses that everywhere.

A class and other composite data types are usually stored with their members only. The bit content would depend on the values of their data members.

So given the following class:

class MyClass
{
  bool  flag;
  int   number;
  double d;
};

The computer would store the 1s and 0s for the flag member, followed by some padding (skipping bytes), followed by the 1s and 0s for the number field, followed by more padding, then followed by the 1s and 0s for the d field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM