C++中头文件的概念与基本编写方法

2020-01-06 14:12:30王冬梅

(4) #include
(5) #endif
(6) 对预处理常量的定义还可以在编译时进行,如CC –D DEBUG main.c
(7)编译C++程序时,编译器自动定义了一个预处理器名字__cplusplus(注意前面有两个下划线),因此可以根据这个来判断该程序是否是C++程序,以便有条件地包含一些代码,如:


#ifndef MYHEAD_H
#define MYHEAD_H
#ifdef __cplusplus
extern "C" {
#endif
int DMpostprocessing();
#ifdef __cplusplus
}
#endif
#endif

(8)在编译C程序时,编译器会自动定义预处理常量__STDC__。当然__cplusplus和__STDC__ 不会同时被定义;
(9)另外两个比较有用的预定义常量是__LINE__(记录文件已经被编译的行数)和__FILE__(包含正在被编译的文件名称)。使用如下:


if(element_count==0)
 cerr<<"Error:"<<__FILE__
   <<":line"<<__LINE__
   <<"element_count must be non-zero.n";

(10) __DATE__:编译日期,当前被编译文件的编译日期
(11) __TIME__:编译时间,当前被编译文件的编译时间
格式如:hh:mm:ss

 08:17:05   Oct 31 2006
(12) C库头文件的C++名字总是以字母C开头,后面去掉.h,如assert.h在C++中为cassert;

assert()是C语言标准库中提供的一个通用预处理器宏。常用其来判断一个必需的前提条件,以便程序能够正确执行。与其关联的头文件是:#include <assert.h>
如:


 assert(filename!=0);

表示:如果后面的程序能够正确执行,需要filename不为0,如是条件为假,即其等于0,断言失败,则程序将输出诊断消息,然后终止。

其c++名字是:cassert
C库头文件的C++名字总是以字母C开头
注:在C++中使用C标准库中的头文件时,一定要使用using namespace std;来使其处在一个名字空间中,才能正确使用

(13)在C++中头文件后缀各不相同,因此标准的C++头文件没有指定后缀

4 C++中的文件输入输出

头文件:#include <fstream>

使用文件输入输出实例:


 #include <fstream>
//为了打开一个输出文件,先声明一个ofstream类型的对象:
 ofstream outfile("name-of-file");
//为了测试是否已经成功打开了一个文件,如下判断:
 //如文件不能打开值为false
 if(!outfile)
   cerr<<"Sorry! We were unable to open the file!n";

//为了打开一个输入文件,先声明一个ifstream类型的对象:
  ifstream infile("name of file");
  if(!infile)
   cerr<<"Sorry! We were unable to open the file!n";

一个简单程序:
  #include <iostream>
  #include <fstream>
  #include <string>

  int main()
  {
   ofstream outfile("out_file");
 ifstream infile("in_file");
 if(!infile){
   cerr<<"error:unable to open input file!n";
   return -1;
 }
 if(!outfile) {
   cerr<<"error:unable to open output file!n";
   return -2;
 }
 string word;
 while (infile>>word)
  outfile<<word<<' ';
 return 0;
  }