C++编程思想 第1卷 第3章 创建复合类型 用struct把变量结合在一起 指针和struct

struct可以当作对象处理 
想存储空间一样,可以取得struct的地址
使用struct的元素,可以使用 .

如果指向struct的指针 可以用 ->来选择元素


//: C03:SimpleStruct3.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Using pointers to structs
typedef struct Structure3 {
  char c;
  int i;
  float f;
  double d;
} Structure3;


int main() {
  Structure3 s1, s2;
  Structure3* sp = &s1;
  sp->c = 'a';
  sp->i = 1;
  sp->f = 3.14;
  sp->d = 0.00093;
  sp = &s2; // Point to a different struct object
  sp->c = 'a';
  sp->i = 1;
  sp->f = 3.14;
  sp->d = 0.00093;
} ///:~


struct sp指向s1
->选择 s1的成员初始化它们
sp指向s2
同样的方式可以初始化变量
指针的好处是可以动态地重定向
指针可以指向不同的对象


无输出

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/80719493