C++复合类型(三)

来源:互联网 发布:新加坡apache国际集团 编辑:程序博客网 时间:2024/06/06 02:00

3rd 结构

定义:

 struct fruit

{

std::string name;

double price;

std::string color

int code;

};

创建类型:

方法一:

fruit apple;

方法二:

struct fruit apple;

方法三:

struct fruit

{

std::string name;

double price;

std::string color

int code;

}apple,banana,kiwi;

 

初始化:(不允许缩窄转换)

方法一:

fruit apple={ “apple”, 8.5, “red”, 1001 };

方法二:

struct fruit

{

std::string name;

double price;

std::string color

int code;

}apple={ “apple”, 8.5, “red”, 1001 };

//逗号的作用是隔开,所以最后一个元素后面没有逗号。

方法三:

fruit banana=apple;

方法四:

fruit apple{ “apple”, 8.5, “red”, 1001 };

//C++11

方法五:

fruit apple={ };

//C++11。各个成员都被设置为零。字符串每个字节都被设置为零。

赋值:

apple={ “apple”, 8.5, “red”, 1001};

apple.name=”apple”;

结构数组:

fruit apple[2]={

{iphone6,6000,black,1001},

{iphone7,8000,white,1101}

};

 

apple[0].name=”apple4”;

 

结构的位字段:

struct fruit

{

unsigned int code:4;//4 bits for code value.

bool flag:1;//1 bit for flag.

};

通常是低级编程中使用位字段的机会更多些。

整形和按位运算可以代替该方法。

By Little_Small_Joze and Katlynn 网络加速 kiwimini.net

原创粉丝点击