如果今天你想定义一个支票帐户,方式之一是:
typedef struct {
String id;
String name;
double balance;
double overdraftlimit;
} CheckingAccount;
这是个很寻常的作法,也许你想将id
、name
与balance
组织在一起,C 语言的结构中允许定义结构:
#include <stdio.h>
typedef const char* String;
typedef struct {
struct {
String id;
String name;
double balance;
} acct;
double overdraftlimit;
} CheckingAccount;
int main() {
CheckingAccount checking = {
.acct = {"123-456-789", "Justin Lin", 1000},
.overdraftlimit = 30000
};
printf("%s\n", checking.acct.id);
printf("%s\n", checking.acct.name);
printf("%f\n", checking.acct.balance);
printf("%f\n", checking.overdraftlimit);
return 0;
}
因为内层的匿名结构用来实例了acct
,因此必须透过acct
来进一步获取内层的值域,你也可以为内层结构命名并用来实例化:
#include <stdio.h>
typedef const char* String;
typedef struct {
struct Account {
String id;
String name;
double balance;
};
struct Account acct;
double overdraftlimit;
} CheckingAccount;
int main() {
CheckingAccount checking = {
.acct = {"123-456-789", "Justin Lin", 1000},
.overdraftlimit = 30000
};
printf("%s\n", checking.acct.id);
printf("%s\n", checking.acct.name);
printf("%f\n", checking.acct.balance);
printf("%f\n", checking.overdraftlimit);
return 0;
}
或者使用已定义的结构来实例化acct
:
#include <stdio.h>
typedef const char* String;
typedef struct {
String id;
String name;
double balance;
} Account;
typedef struct {
Account acct;
double overdraftlimit;
} CheckingAccount;
int main() {
CheckingAccount checking = {
.acct = {"123-456-789", "Justin Lin", 1000},
.overdraftlimit = 30000
};
printf("%s\n", checking.acct.id);
printf("%s\n", checking.acct.name);
printf("%f\n", checking.acct.balance);
printf("%f\n", checking.overdraftlimit);
return 0;
}
看来还不错,不过,如果想要checking.name
就能获取名称的话,可以直接内嵌结构类型:
#include <stdio.h>
typedef const char* String;
typedef struct {
String id;
String name;
double balance;
} Account;
typedef struct {
struct {
String id;
String name;
double balance;
};
double overdraftlimit;
} CheckingAccount;
int main() {
CheckingAccount checking = {
{"123-456-789", "Justin Lin", 1000},
.overdraftlimit = 30000
};
printf("%s\n", checking.id);
printf("%s\n", checking.name);
printf("%f\n", checking.balance);
printf("%f\n", checking.overdraftlimit);
return 0;
}
CheckingAccount
中有个匿名结构,匿名结构的成员会被视为外包结构的成员,也就可以如上访问,也可以将另一个已定义的结构嵌入:
#include <stdio.h>
typedef const char* String;
typedef struct {
String id;
String name;
double balance;
} Account;
typedef struct {
Account;
double overdraftlimit;
} CheckingAccount;
int main() {
CheckingAccount checking = {
{"123-456-789", "Justin Lin", 1000},
.overdraftlimit = 30000
};
printf("%s\n", checking.id);
printf("%s\n", checking.name);
printf("%f\n", checking.balance);
printf("%f\n", checking.overdraftlimit);
return 0;
}