less than 1 minute read

整理自 Thinking in C++。没啥特别好说的。


1. 起手式

struct Structure1 {
	char c;
	int i;
};

int main() {
	struct Structure1 s1; // 不需要 new
	s1.c = 'a'; // access an element using a '.'
	s1.i = 1;
	
	struct Structure1* ps1 = &s1;
	ps1->c = 'b'; // access an element using a '->'
	ps1->i = 2;
}
  • 注意 define 要写全名 struct Structure1 s1;
  • 然后 struct variable 访问 member 直接用 s1.c
  • struct pointer 访问 member 要用 ps1->c

2. typedef 式

typedef struct {
	char c;
	int i;
} Structure2;

int main() {
	Structure2 s1;
	s1.c = 'a';
	s1.i = 1;
}

typedef + struct 连写,清爽多了

3. typedef 式进阶

typedef struct SelfReferential {
	int i;
	SelfReferential* sr; // 我还没 def 完,你就直接拿来用了……
} SelfReferential;

int main() {
	SelfReferential sr1, sr2;
	sr1.sr = &sr2;
	sr2.sr = &sr1;
	sr1.i = 47;
	sr2.i = 1024;
}

不要问我为什么可以这样用……

Categories:

Updated:

Comments