码迷,mamicode.com
首页 > 编程语言 > 详细

C++ "hello world‘实例

时间:2015-10-06 16:38:03      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:

1. hello world实例

#include <iostream>
main()
{
std::cout<<"hello world"<<std::endl; 
}

或者:

#include <iostream>
using namespace std;
int main()
{
cout<<"hello world"<<endl;
}

save as: foo.cpp

compile: g++ -o foo foo.cpp

run: ./foo

 

2. 搞不懂,不能直接g++ foo.cpp

为什么是<iostream>而不是<iostream.h> ?

为什么要加std:: ?

std是一个类(输入输出标准),它包括了cin成员和cout成员,using name space std ;以后才能使用它的成员。#include<iostream.h>中不存在类std,但是他又cin,out的相关函数,不需要使用命名空间了。而第二种标准#include<iostream>,它包含了一个类,在类的使用之前要预处理一下,using namespace std;就是这个功能,然后你就可以使用cin,cout这两个成员函数了,假设你不使用预处理(using namespace std;),麻烦加上std::cin或者std::cout再去使用它的成员函数(头文件中存在这个类)
提问者评价

3.

#include <iostream.h>非标准输入输出流
#include <iostream>标准输入输出流

C++中为了避免名字定义冲突,特别引入了“名字空间的定义”,即namespace。
当代码中用<iostream.h>时,输出可直接引用cout<<x;//<iostream.h>继承C语言的标准库文件,未引入名字空间定义,所以可直接使用。
当代码中引入<iostream>时,输出需要引用std::cout<<x;如果还是按原来的方法就会有错。
使用<iostream>时,引入std::有以下方法:

1.
using namespace std;
cout<<x;
2.
using std::cout;
cout<<x;
3.
最基本的std::cout<<x;

这回你该知道为什么通常用#include <iostream>时,
要用using namespace std;了吧。如果你不用这个,就要在使用cout时,用后两种方法了。
其他头文件也是同样的道理。
(有“.h”的就是非标准的,C的标准库函数,无“.h”的,就要用到命令空间,是C++的。还有一部分不完全是有“.h”和没“.h”的差别。例如:math.h和cmath) 

C++ "hello world‘实例

标签:

原文地址:http://www.cnblogs.com/htmlphp/p/4857222.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!