C++杂记之struct, Union, Enum

为什么要引入结构体呢?
答:Suppose you want to store information about a basketball player.Y ou might want to store
his or her name, salary, height, weight, scoring average, free-throw percentage, assists, and
so on.Y ou’d like some sort of data form that could hold all this information in one unit.
An array won’t do.Although an array can hold several items, each item has to be the same
type.That is, one array can hold 20 int s and another can hold 10 float s, but a single
array can’t store int s in some elements and float s in other elements.

struct Student
   {
       string name;
       int age;
       string sex;
   };

#与c不同,我们实例化结构体不需要 加struct关键字
然后我们实例化与java等不同不能用: Student student1 = new Student("haah", 23, "female");
而是的用: Student student ={"weilin", 23, "male"};  #在C++11中赋值 = 可以omit(省略啦)
我们可以用 . 来获取其的成员变量
cout << student.name;

#结构体的嵌套
struct Costs
{
    double wholesale;
    double retail;
};
struct Item
{
    string partNum;
    string description;
    Costs pricing;
};

访问retailItem.pricing.retail

总结不像python 有getattr() 和 delattr() 对其进行操作

Unions:
A union is a data format that can hold different data types but onThat is, whereas a structure can hold, say, an int and a long and hold an int or a long or a double .The syntax is like that for a stis different. For example, consider the following declaration:(每次只能存储一个值)



Enumerations:
The C++ enum facility provides an alternative to const for creating symbolic constants. Italso lets you define new types but in a fairly restricted fashion.The syntax for enumresembles structure syntax. For example, consider the following statement:
enum spectrum {red, orange, yellow, green, blue, violet, indigo, ultraviolet};
spectrum band;
band = blue;       // valid, blue is an enumerator
band = 2000;       // invalid, 2000 not an enumerator
band = orange;           // valid
++band;                  // not valid, ++ discussed in Chapter 5
band = orange + red;     // not valid, but a little tricky
int color = blue;        // valid, spectrum type promoted to int
band = 3;                // invalid, int not converted to spectrum
color = 3 + red;         // valid, red converted to int

神奇的是:
enum bits{one = 1, two = 2, four = 4, eight = 8};
bits myflag;
In this case, the following is valid:
myflag = bits(6);    // valid, because 6 is in bits range,这就很有意思,有木有
int main()
{
   enum VIP{
        blue = 1,
        orange = 2,
        red = 3
    };
   
    cout << VIP(blue); #1
    cout << VIP(1); #1
}

相比于python:
from enum import IntEnum
class VIP(IntEnum):
    YELLOW = 1
    GREEN = 2
    RED = 3
print(VIP.YELLOW) #VIP.YELLOW
print((VIP(1))) #VIP.YELLOW
print(type(VIP.RED)) #<enum 'VIP'>

猜你喜欢

转载自blog.csdn.net/qq_37982109/article/details/88657699