f(sixleaves) = sixleaves

重剑无锋 大巧不工

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  95 随笔 :: 0 文章 :: 7 评论 :: 0 Trackbacks
回顾:在第0章中我总结了重要的知识点有:字符串直接量、表达式的结构,操作数和操作符的定义,还有表达式的副作用、和std::cout结合<<操作符返回std::ostream类型,等知识点。
代码如下
 1 // ask for person's name, and greet the person
 2 
 3 #include <iostream>
 4 #include <string>
 5 
 6 int main() {
 7     //ask for the person's name
 8     std::cout << "Please enter your first name: ";
 9 
10     //read the name
11     std::string name;
12     std::cin >> name;
13 
14     //write a greeting
15     std::cout << "Hello, " << name << "!" << std::endl;
16     return 0;
17 }
#name就是一个变量(它的类型是std::string),而变量是一个有名字的对象(变量一定是对象,但对象不一定为变量,因为对象可以没有名字,而且对象对应系统中的一块内存)。
#line 11:是一个definition,即是一个定义,定义了一个名叫做name的std::string类型的变量。而且出现在一个函数提中,所以是一个local variable,当程序执行放到},就会销毁name变量,并且释放name占用的内存,以让其他变量使用。
#line 12:>>从标准输入中读取一个字符串,并且保存它在name对象中。当通过标准库读取一个字符串时,他会忽略输入中的所有空白符,而吧其他字符读取到name中,直到它遇到其他空白符或者文件结束标志。因此std::cin >> name;的结果是从标准输入中读取一个单词。
#输入输出库会把它的输出保存在buffer的内部数据结构上,通过缓存可以优化输出操作。(因为许多操作系统在向输出设备写入字符时需要花大量的时间)
#有三个事件会促使系统刷新缓冲区。
 #第一,缓存区满了,自动刷新。
 #第二,标准库被要求读取标准输入流。(即std::cin是std::istream类型)。如line 12.
 #第三,显示的要求刷新缓冲。(std::endl结束了输出行,并且刷新缓冲区)
# 1 //ask for a person's name, and generate a framed greeting
 2 #include <iostream>
 3 #include <string>
 4 
 5 int main() {
 6     std::cout << "Please enter your first name: ";
 7     std::string name;
 8     std::cin >> name;
 9     //build the message that we intend to write
10     const std::string greeting = "Hello, " + name + "!";
11 
12     //build the second and fourth lines of the input
13     const std::string spaces(greeting.size(), ' ');
14     const std::string second = "* " + spaces + " *";
15 
16     //build the first and fifth lines of the output
17     const std::string first(second.size(), '*');
18 
19     //write it all
20     std::cout << std::endl;
21     std::cout << first <<std::endl;
22     std::cout << second << std::endl;
23     std::cout << "* " << greeting << " *" << std::endl;
24     std::cout << second << std::endl;
25     std::cout << first << std::endl;
26 
27     return 0;
28 }
#greeting的定义包含三个新的概念
  #第一个:在定义变量时候,可以给定它的值。
  #第二个:用+来连接字符串,但是这两个中必须至少有一个是string对象。(+也是左结合性的)
   #(+在这里是连接作用),引出overloaded(重载)概念,这个操作符被重载了,因为其对不同操作数有不同的含义。
  #第三个:const可以作为变量定义的一部分,这么做保证在变量生存期内,不改变它的值。
   #如果一个变量定义为const,必须在定义时初始化,否则后面就不能再初始化。
#const std::string spaces(greeting.size(), ' ');来介绍另三个概念
  #第一个:构造函数
  #第二个:成员函数(member function),其实可以吧greeting看成对象,向其发送size消息获取其长度。
  #第三个:字符直接量。(用'(单引号),而字符串直接量则是用“号).字符直接量的类型是内置于语言核心的char类型。
posted on 2014-02-20 20:38 swp 阅读(181) 评论(0)  编辑 收藏 引用 所属分类: program language

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理