[C++]cpp小笔记3 --- C++ Structures

注:语法:在头文件中的变量,只有static const类型的变量才能被初始化!!


1. Struct的声明。


在头文件中:
public:
	struct Person {
		char name[20];
		int height;
		int weight;
	};

	struct Food {
		string name;
		int weight;
	} orange, apple;

	struct Point {
		int x;
		int y;
	} point;
	struct Circle {
		Point point;
		int radius;
	};
	struct {
		string name;
	} test;
注意最后一个test因为没有定义struct type name,所以这个struct无法在后面在定义新的类型。

2. Struct的使用

	Person me = {"x", 187, 190};
	Person Parents[] = {
			{"y", 166, 100},
			{"z", 170, 150}
	};
	cout << "Person: " << me.name <<" is " << me.height << " tall and " << me.weight <<" weight"<< endl;
	int size = sizeof(Parents) / sizeof(Person);
	for(int i = 0; i < size; i ++) {
		cout << "Person: " << Parents[i].name <<" is " << Parents[i].height << " tall and " << Parents[i].weight <<" weight"<< endl;
	}
	apple = {"apple", 12};
	orange = {"orange", 13};
	cout << "Food: " << orange.name <<" is " << orange.weight <<" weight"<< endl;
	Food banana={"banana", 14};
	Food strawberry;

	strawberry.name="strawberry";
	strawberry.weight = 18;
        Circle circle= {{10,20}, 20};
	cout << "The point of a circle is "<<circle.point.x << " and " <<circle.point.y << " ,and radius is" << circle.radius<<endl;


use pointer to access structures
Point * point;
point->x = 10;
point->y = 20;


你可能感兴趣的:(C++)