struct是一组数据元素一个名字,这些数据元素,作为成员,可以有不同类型和不同长度。C++声明struct语法如下:
struct structure_name { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3; . . } object_names;
简单示例如下:
struct product { int weight; float price; } ;
product apple; product banana, melon;
声明struct并定义多个实例:
struct product { int weight; float price; } apple, banana, melon;
完整struct例子:
// example about structures #include <iostream> #include <string> #include <sstream> using namespace std;
struct movies_t { string title; int year; } mine, yours;
void printmovie (movies_t movie);
int main () { string mystr;
mine.title = "2001 A Space Odyssey"; mine.year = 1968;
cout << "Enter title: "; getline (cin,yours.title); cout << "Enter year: "; getline (cin,mystr); stringstream(mystr) >> yours.year;
cout << "My favorite movie is:\n "; printmovie (mine); cout << "And yours is:\n "; printmovie (yours); return 0; }
void printmovie (movies_t movie) { cout << movie.title; cout << " (" << movie.year << ")\n"; }
struct和指针
struct movies_t { string title; int year; };
movies_t amovie; movies_t * pmovie; pmovie = &amovie;
完整示例如下:
// pointers to structures #include <iostream> #include <string> #include <sstream> using namespace std;
struct movies_t { string title; int year; };
int main () { string mystr;
movies_t amovie; movies_t * pmovie; pmovie = &amovie;
cout << "Enter title: "; getline (cin, pmovie->title); cout << "Enter year: "; getline (cin, mystr); (stringstream) mystr >> pmovie->year;
cout << "\nYou have entered:\n"; cout << pmovie->title; cout << " (" << pmovie->year << ")\n";
return 0; }
内部struct
struct movies_t { string title; int year; };
struct friends_t { string name; string email; movies_t favorite_movie; } charlie, maria;
friends_t * pfriends = &charlie;
使用如下:
charlie.name maria.favorite_movie.title charlie.favorite_movie.year pfriends->favorite_movie.year
union
union允许以不同的数据类型访问相同的内存,因为他们实际上是在内存中的相同位置,它的声明和struct差不多,但功能完全不同:
union union_name { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3; . . } object_names;
union声明的所有元素在内存中占有相同的物理空间,其大小是该声明的最大元素的大小:
union mytypes_t { char c; int i; float f; } mytypes;
每一个不同的数据类型。由于所有的元素都指的是内存中的同一位置,修改的内容之一,会影响其他元素的内容。
匿名union
struct和正常union
struct { char title[50]; char author[50]; union { float dollars; int yen; } price; } book;
struct和匿名union
struct { char title[50]; char author[50]; union { float dollars; int yen; }; } book;
第一种类型的访问方式,如下:
book.price.dollars book.price.yen
第二种类型的访问方式,如下:
enum
定义枚举类型的基本语法:
enum enumeration_name {
value1,
value2,
value3,
.
.
} object_names;
例如:
enum Week {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};
其中SUNDAY = 0,MONDAY = 1……SATURDAY = 6。也就是说,第1个枚举值代表0,第2个枚举值代表1,这样依次递增1。
也可以在定义时,直接指定某个或某些枚举值的数值,例如:
enum Week {MONDAY = 1,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY};
其中MONDAY等于1,这样,TUESDAY就将等于2,直接到SUNDAY等于7。
声明枚举变量:
枚举值,我们就称为格举常量,因为它一经定义以后,就不可再改变,以下用法是错误的!
TUESDAY = 10; //错误!我们不能改变一个枚举值的数值。
|
请发表评论