我这样把【结构体】的【成员】加起来有什么问题吗?
定义了一个结构体:
struct WARNING_FLAG //报警
{
unsigned int Weight;//吊重
unsigned int Moment;//力矩
unsigned int Span; //限幅
unsigned int Lifting; //起升
unsigned int Rotary; //回转
unsigned int collide; //碰撞
unsigned int Wind; //风速
unsigned int DipAngle; //倾角
unsigned int Hight;//高度
};
int testint=0;
unsigned int *testp; //定义了一个指针
testp=&WARN.Weight; //把结构体第一个成员的地址给了指针
for(int i=0;i<9;i++)
{
testint=testint+*testp;
testp++;
}
//这样累加, 结构符合预期。
结构符合预期,但是我不知道我这样做何不合理,有没有什么隐患?书上没有说到这个
[解决办法]
testp=&WARN.Weight;
最好改成testp=(unsigned int *)&WARN.Weight;
我感觉最好不要这么做,虽然语法上没啥问题,如果以后有人修改你的程序,修改了这个结构,比如加了个浮点型,就会出问题,而且还不好找,因为这个问题编译器是无法找到的。
[解决办法]
#include "stdafx.h"#include <iostream>using namespace std;struct WARNING_FLAG //报警{ unsigned int Weight; //吊重 unsigned int Moment; //力矩 unsigned int Span; //限幅 unsigned int Lifting; //起升 unsigned int Rotary; //回转 unsigned int collide; //碰撞 unsigned int Wind; //风速 unsigned int DipAngle; //倾角 unsigned char Hight; //高度};int _tmain(int argc, _TCHAR* argv[]){ int testint=0; unsigned int *testp; //定义了一个指针 WARNING_FLAG WARN; const unsigned int COUNT = 8; WARN.Weight = COUNT; WARN.Moment = COUNT; WARN.Span = COUNT; WARN.Lifting = COUNT; WARN.Rotary = COUNT; WARN.collide = COUNT; WARN.Wind = COUNT; WARN.DipAngle = COUNT; WARN.Hight = COUNT; testp=&WARN.Weight; //把结构体第一个成员的地址给了指针 for(int i=0;i<9;i++) { testint=testint+*testp; testp++; } //这样累加, 结构符合预期。 cout<<hex<<(unsigned int)testint<<endl; testint = WARN.Weight + WARN.Moment + WARN.Span + WARN.Lifting + WARN.Rotary +WARN.collide + WARN.Wind + WARN.DipAngle + WARN.Hight; cout<<hex<<(unsigned int)testint<<endl; cout<<hex<<testint - WARN.Hight<<endl; return 0;}
[解决办法]
感觉应该行,不过保险起见,应该进行下强制类型转换!