C++ Primer學習筆記第4章複合類型

4.4.1 在程序中使用結構

//structur.cpp -- a simple structure
#include <iostream>
struct inflatable // structure declaration
{
	char name[20];
	float volume;
	double price;
};

int main(){
	using namespace std;
	inflatable guest = {
		"Gloridous Gloria",//name value
		1.88,				//volume value
		29.99				//price value
	};	//guest is a structure variable of type inflatable
//It's initialized to the indicated values
	inflatable pal = {
		"Audacious Arthur",
		3.12,
		32.99
	};//pal is a second variable of type inflatable
//Note:some implementations require using 
//static inflatable guest = 
	cout << "Expand your guest list with " << guest.name;
	cout << " and " << pal.name << "!\n";
	//pal.name is the name member of the pal variable
	cout << "You can have both for $";
	cout << guest.price + pal.price << "!\n";
	return 0;
}

下面是程該程序的輸出:

Expand your guest list with Gloridous Gloria and Audacious Arthur!
You can have both for $62.98!

4.4.5 結構數組

程序清單4.13  arrstruc.cpp

//structur.cpp -- a simple structure
#include <iostream>
struct inflatable // structure declaration
{
	char name[20];
	float voluem;
	double price;
};

int main() {
	using namespace std;
	inflatable guests[2] =
	{
		{"Bambi",0.5,21.99},
		{"Godzilla", 2000, 565.99}
	};

	cout << "The guesta " << guests[0].name << " and " << guests[1].name
		<< "\n have a combind volume of "
		<< guests[0].voluem + guests[1].voluem << " cubic feet.\n";
	return 0;
}

下面是該程序的輸出:

The guesta Bambi and Godzilla
have a combind volume of 2000.5 cubic feet.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章