学学习网 手机版

学学习网

学习路径: 学习首页 > 应用开发 > c++ >

第五节 数组 (Arrays)(11)

设置字体:
----------------------------------

在结构定义的结尾可以加可选项object_name ,它的作用是直接声明该结构类型的对象。例如,我们也可以这样声明结构对象apple, orange和melon:
struct products {
char name [30];
float price;
}apple, orange, melon;
并且,像上面的例子中如果我们在定义结构的同时声明结构的对象,参数model_name (这个例子中的products)将变为可选项。但是如果没有model_name,我们将不能在后面的程序中用它来声明更多此类结构的对象。
清楚地区分结构模型model和它的对象的概念是很重要的。参考我们对变量所使用的术语,模型model 是一个类型type,而对象object 是变量variable。我们可以从同一个模型model (type)实例化出很多对象objects (variables)。
在我们声明了确定结构模型的3个对象(apple, orange 和 melon)之后,我们就可以对它们的各个域(field)进行操作,这通过在对象名和域名之间插入符号点(.)来实现。例如,我们可以像使用一般的标准变量一样对下面的元素进行操作:
apple.name
apple.price
orange.name
orange.price
melon.name
melon.price
它们每一个都有对应的数据类型:apple.name, orange.name 和melon.name 是字符数组类型char[30],而apple.price, orange.price 和 melon.price 是浮点型float。
下面我们看另一个关于电影的例子:
// example about structures
#include ‹iostream.h›
#include ‹string.h›
#include ‹stdlib.h›

struct movies_t {
char title [50];
int year;
}mine, yours;

void printmovie (movies_t movie);

int main () {
char buffer [50];
strcpy (mine.title, "2001 A Space Odyssey");
mine.year = 1968;
cout << "Enter title: ";
cin.getline (yours.title,50);
cout << "Enter year: ";
cin.getline (buffer,50);
yours.year = atoi (buffer);
cout << "My favourite movie is:\n ";
printmovie (mine);
cout << "And yours:\n";
printmovie (yours);
return 0;
}

void printmovie (movies_t movie) {
cout << movie.title;
cout << " (" << movie.year << ")\n";
}
Enter title: Alien
Enter year: 1979
My favourite movie is:
2001 A Space Odyssey (1968)
And yours:
Alien (1979)
这个例子中我们可以看到如何像使用普通变量一样使用一个结构的元素及其本身。例如,yours.year 是一个整型数据int,而 mine.title 是一个长度为50的字符数组。
注意这里 mine 和 yours 也是变量,他们是movies_t 类型的变量,被传递给函数printmovie()。因此,结构的重要优点之一就是我们既可以单独引用它的元素,也可以引用整个结构数据块。
结构经常被用来建立数据库,特别是当我们考虑结构数组的时候。
// array of structures
#include ‹iostream.h›
#include ‹stdlib.h›

#define N_MOVIES 5

struct movies_t {
char title [50];
int year;
} films [N_MOVIES];

void printmovie (movies_t movie);

int main () {
char buffer [50];
int n;
for (n=0; n<N_MOVIES; n++) {
cout << "Enter title: ";
cin.getline (films[n].title,50);
cout << "Enter year: ";
cin.getline (buffer,50);
films[n].year = atoi (buffer);
}

cout << "\nYou have entered these movies:\n";
for (n=0; n<N_MOVIES; n++) {
printmovie (films[n]);
return 0;
}

void printmovie (movies_t movie) {
cout << movie.title;
cout << " (" << movie.year << ")\n";
}

 
Enter title: Alien
Enter year: 1979
Enter title: Blade Runner
Enter year: 1982
Enter title: Matrix
Enter year: 1999
Enter title: Rear Window
Enter year: 1954
Enter title: Taxi Driver
Enter year: 1975

You have entered these movies:
Alien (1979)
Blade Runner (1982)
Matrix (1999)
Rear Window (1954)
Taxi Driver (1975)
 
----------------------------------
课程列表
重点难点
赞助链接