[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;


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值