編輯器:UltraEdit18編譯器:g++4.4.3、gcc4.4.3編譯環境:ubuntu10.0
作業練習:
簡單的C++結構體嵌套的使用,以及結構體大小和空結構體,使用g++編譯
#include //cout
#include
#define NSIZE 128
using namespace std;
struct SubStruct
{
char *str;
double dVal;
};
#if 0
struct MyStruct
{
void Hello();
int ID;
char *name;
struct SubStruct sub;
};
#endif //0
typedef struct MyStruct
{
void Hello();
int ID;
char *name;
struct SubStruct sub;
}mystruct;
void MyStruct::Hello()
{
cout << "hello struct, nice to me you!" << endl;
cout << "my name is:" << name << '\t' << "my id is:" << ID << endl;
cout << sub.str << endl;
}
/*結構體X、Y、Z*/
struct X
{
int XID;
char Xsymb;
float Xf;
};
struct Y
{
long Ysize;
int YID;
double Yd;
};
struct Z
{
char Zsymb;
double Zd;
int ZID;
};
struct Empty
{
};
/****************/
/*空類大小*/
class CMyclass
{
};
/***********/
int main()
{
MyStruct A;//mystruct C++中不需要typedef或struct MyStruct xxx
A.ID = 10;
A.name = (char *)"lqf";
A.sub.str = (char *)"I am substruct";
A.Hello();
cout << A.sub.str << endl;
#if 0
/*計算結構體X、Y、Z和MyStruct大小*/
cout << "size of struct MyStruct:" << sizeof(struct MyStruct) << endl;//20
cout << "size of struct X:" << sizeof(struct X) << endl;//12
cout << "size of struct Y:" << sizeof(struct Y) << endl;//16
cout << "size of struct Z:" << sizeof(struct Z) << endl;//16
cout << "size of struct Empty:" << sizeof(struct Empty) << endl; //1
cout << "size of class Empty:" << sizeof(class CMyclass) << endl; //1
/**********************/
#endif //0
return 0;
}
#include
#define NSIZE 128
struct SubStruct
{
char *str;
};
struct MyStruct
{
int ID;
char *name;
struct SubStruct sub;
};
/*結構體X、Y、Z*/
struct X
{
int XID;
char Xsymb;
float Xf;
};
struct Y
{
long Ysize;
int YID;
double Yd;
};
struct Z
{
char Zsymb;
double Zd;
int ZID;
};
struct Empty
{
};
/****************/
int main()
{
/*計算結構體X、Y、Z大小*/
printf("size of struct X:%d\n",sizeof(struct X));
printf("size of struct Y:%d\n",sizeof(struct Y));
printf("size of struct Z:%d\n",sizeof(struct Z));
printf("size of struct Empty:%d\n",sizeof(struct Empty));
/**********************/
return 0;
}