从C看C++之(一)HelloWorld

来源:互联网 发布:php新闻发布系统coon 编辑:程序博客网 时间:2024/06/08 06:42

    接下来的工作要涉及到C++方面的知识,从头学起就不太现实了.来点投机取巧的方式吧.

 目标:在终端打印出"Hello,World!".

 源码:

#include <iostream><pre id="answer-content-1625958308" class="answer-text mb-10">using namespace std;
int main(void){ const char *pChar = "Hello,World!"; std::cout << pChar << std::endl; return 0;}
 编译:

root@se7en-LIFEBOOK-LH531:~/learn/Cpp_Program# g++ helloWorld.cpp -o helloWorldroot@se7en-LIFEBOOK-LH531:~/learn/Cpp_Program# 
 运行:

root@se7en-LIFEBOOK-LH531:~/learn/Cpp_Program# ./helloWorld Hello,World!root@se7en-LIFEBOOK-LH531:~/learn/Cpp_Program# 


 问题点:


1.头文件是<iostream>而不是<iostream.h>;2.对字符串要加关键字const,否则编译器给出警告.而C中不会;3.输出流不再使用C里面的printf()函数,而是使用"std::cout << xx << std::endl"4.using namespace std;就是告诉编译器,这行代码之后用到的cout、cin等函数都是std这个命名空间内定义的.

   

    扩展:

 很多时候,为了方便,例如读取出来的寄存器,我们都会以十六进制打印出来,这样就比较直观.因此,了解C++下指定格式输出就很必要了.下面是一个把十进制的数据按十六进制输出.

 源码:

#include <iostream>using namespace std;int main(void){        unsigned int i = 100;        std::cout << hex << std::endl;        std::cout << "0x" << i << std::endl;        return 0;}
 编译运行:

root@se7en-LIFEBOOK-LH531:~/learn/Cpp_Program# g++ helloWorld.cpp -o helloWorldroot@se7en-LIFEBOOK-LH531:~/learn/Cpp_Program# ./helloWorld 0x64root@se7en-LIFEBOOK-LH531:~/learn/Cpp_Program# 

 


  

0 0
原创粉丝点击