忆江南-春风

象蜗牛一样生活
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

开始学习C++(一)

Posted on 2013-10-05 23:23  忆江南-春风  阅读(196)  评论(0编辑  收藏  举报

刚开始学习c++,下面写了一个小例子myfirst.cpp:

  1 //my first c++ progream
  2 #include<iostream>
  3
  4 int main(){
  5         using namespace std ;
  6         cout << "Come up and C++ me some time." ;
  7         cout << endl ;
  8         cout << "You won't regret it!" << endl ;
  9
 10         return 0 ;
 11 }

下面对myfirst.cpp文件做一些分析:

  注释://是单行注释,/*…………*/是多行注释,程序会忽略这部分内容。

  预处理命令:以#开头是预处理命令,在源代码编译之前,替换或添加文本。如:

    #include<iostream>是在编译之前,将iostream头文件的内容添加到该预处理命令所在位置。

    #define SIZE 0  是在编译之前,将源文件中的SIZE替换为0进行处理。

  主函数:int main(){    return 0 ;}是主函数,每个程序都应该包含main函数。

  头文件:iostream是标准头文件,要在程序中使用,应该使用#include包含命令,标准头文件使用<>包含,自定义头文件使用""双引号包含。

  命名空间:using namespace std ;在大程序中,为了更好的组织程序,使用命名空间,如在名称空间AA中包含print函数,在名称空间BB中也包含print函数,可以使用AA::print()和BB::print()进行区分。

 1 #include<iostream>
 2 
 3 namespace AA{
 4         void print(){
 5                 std::cout << "Hello AA!!!" << std::endl ;
 6         }
 7 }
 8 
 9 namespace BB{
10         void print(){
11                 std::cout << "Hello BB!!!" << std::endl ;
12         }
13 }
14 
15 int main(){
16         AA::print() ;
17 
18         BB::print() ;
19         return 0 ;
20 }

使用using编译指令是一种偷懒的做法:using namespace std ;    在使用std命名空间的内容时就可以不加std::前缀了。
换行符:endl是c++在iostream头文件中定义的换行符,在换行时会刷新输出缓冲区。'\n'是c语言的换行符,主要在字符串中使用。

如:cout << "name :" << name << "\naddress: " << address << endl ;

cout : iostream头文件中定义的标准输出对象,使用<<输出基本类型和复合类型,复合类型需要定义<<符号操作函数。输出时会先将要输出的内容放在输出缓冲区,然后cout从输出缓冲区中取内容进行输出。

cin:iostream头文件中定义的标准输入对象,使用>>输入基本类型和复合类型,复合类型需要定义>>操作符。输入时先将要输入的内容放在输入缓冲区,然后在从输入缓冲区中取内容进行输入。取完或遇到不符合的内容结束。如:

#include<iostream>

using namespace std ;

int main(){
        char name[50] ;
        int age = 0 ;
        double sal = 0.0 ;

        cout << "Enter your name:" ;
        cin >> name ;
        cout << "Enter your age:" ;
        cin >> age ;
        cout << "Enter your sal:" ;
        cin >> sal ;

        cout << "Your informtion:"
             <<"\n\tname: " << name
             <<"\n\tage: " << age
             <<"\n\tsal: " << sal << endl ;

        return 0 ;
}

在我们输入age时若输入23.5,则age=23,缓冲区中有0.5,则会输入到sal中。

[root@localhost cheptor01]# ./testCout.out
Enter your name:xushuangzhi
Enter your age:23.5
Enter your sal:Your informtion:
        name: xushuangzhi
        age: 23
        sal: 0.5

c++程序的处理过程:

  编辑->编译->链接->可执行文件。

  -c : 编译     g++  myfirst.cpp -c     对myfirst.cpp源文件进行编译 生成myfirst.o文件    可以对多个文件进行编译   g++ file1.cpp file2.cpp -c

  -o : 链接     g++ myfirst.o -o myfirst.out     进行链接  生成myfirst.out可执行文件。  也可以对多个文件进行链接。

  g++ myfirst.cpp -o myfirst.out    直接生成可执行文件。

linux常用命令:

  cd /usr/c++  进入/usr/c++目录

  rm myfirst.cpp   删除myfirst.cpp文件     -r   删除目录下的文件

  touch myfirst.cpp   创建myfirst.cpp文件 

  mkdir   test    创建test目录

  rmdir test      删除test目录    当目录不为空时,可以使用rm -r test 删除目录下的文件    然后再删除该目录。

  .   当前目录

  ..  上级目录

  /跟目录

  ~当前用户目录