设为首页 加入收藏

TOP

6.3 结构(2)
2013-10-07 00:48:15 来源: 作者: 【 】 浏览:54
Tags:6.3 结构

6.3 结构(2)

对于整数、浮点数或其他标量的变量类型,我们都可以通过对指针进行解引用来访问相应的变量值,如下所示:

  1. int myInt = 10;  
  2. int *myPtr = &myInt;  
  3. *myPtr = 45; 

对于指向结构的指针,我们需要使用上述语法的一种变体:

  1. (*myself).age = 41;  
  2. std::cout << (*myself).gender; 

如果你觉得这样的代码不够美观,可以换用下面这种语法:

  1. ptrName->memberName; 

也就是……

  1. myself->age = 41;  
  2. std::cout << myself->gender; 

定义并使用结构

1.在文本编辑器或IDE里创建一个新的、空白的文本文档(代码清单6-6)。

  1. // books.cpp - Script 6.6  
  2. #include  

代码清单6-6 用一个结构来创建一种用户定义的变量类型,新类型的名字是book,它把图书的书名、作者和出版日期封装在同一个变量名下

  1. 1   // books.cpp - Script 6.6  
  2. 2     
  3. 3   #include   
  4. 4     
  5. 5   // Define the structure.  
  6. 6   struct book {  
  7. 7     
  8. 8       // Define the members.  
  9. 9       std::string title;  
  10. 10      std::string author;  
  11. 11      unsigned int year;  
  12. 12        
  13. 13  }; // Don't forget the semicolon!  
  14. 14        
  15. 15  int main() {  
  16. 16    
  17. 17      // Create a new variable.  
  18. 18      book book1;  
  19. 19        
  20. 20      // Prompt the user for the title.  
  21. 21      std::cout << "Enter the book's title:\n";  
  22. 22      std::getline(std::cin, book1.title);  
  23. 23    
  24. 24      // Prompt the user for the author.  
  25. 25      std::cout << "Enter the book's author:\n";  
  26. 26      std::getline(std::cin, book1.author);  
  27. 27    
  28. 28      // Prompt the user for the publication year.  
  29. 29      std::cout << "Enter the book's publication year: ";  
  30. 30      std::cin >> book1.year;  
  31. 31        
  32. 32      // Repeat the input.  
  33. 33      std::cout << "\nThe following information has been received..." 
  34. 34      << "\nTitle: " << book1.title  
  35. 35      << "\nAuthor: " << book1.author  
  36. 36      << "\nYear: " << book1.year << "\n\n";  
  37. 37    
  38. 38      // Discard any extraneous input.  
  39. 39      std::cin.ignore(100, '\n');  
  40. 40      std::cout << "Press Enter or Return to continue.\n";  
  41. 41      std::cin.get();  
  42. 42      return 0;  
  43. 43        
  44. 44  } // End of the main() function. 

2.定义必要的结构。

  1. struct book {  
  2.     std::string title;  
  3.     std::string author;  
  4.     unsigned int year;  
  5. }; 

这个结构的名字是book,包含3个成员:一个名为title的字符串、一个名为author的字符串和一个用来保存图书出版年份的无符号整数变量year。千万不要漏掉右花括号后面的分号,否则就会在编译这个程序时看到一些警告消息(如图6-17所示)。

 
图6-17 如果在定义一个结构时漏掉了最末尾的分号,
你将看到如图所示的警告消息
我们是在任何函数之外和之前(而不是在某个函数的内部)定义这个结构的,所以可以在任何一个函数里使用它。
【责任编辑:云霞 TEL:(010)68476606】

回书目   上一节   下一节

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇6.3 结构(3) 下一篇6.3 结构(1)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: