zoukankan      html  css  js  c++  java
  • 程序由多个文件组成时、 头文件

    为允许把程序分成独立地逻辑块,C++支持所谓的分别编译(separation compilation),这样程序可以有多个文件组成。

    头文件为相关声明 提供了一个集中存放的位置。头文件一般包含类的定义、extern变量的声明和函数的声明,头文件经常#include其他头文件。使用或定义这些实体时需要包相应的头文件。

    头文件用于声明而不是用于定义:

    因为头文件包含在多个源文件中,并且定义只可以出现一次,所以头文件不该含有变量或函数的定义

    但头文件不还含有定义这一规则有3个例外。头文件可以定义类,值在编译时就已知的const对象(不可变的变量,相当于常量)和inline函数(内联函数)

    #include设施是C++预处理器(preprocessor)的一部分,预处理器在编译器前运行,处理程序的源代码。

    在编写头文件前,需引入一些额外的预处理器设施。预处理器允许我们自定义变量。

    预处理器变量(也称预处理器常量)的名字在程序中必须是唯一的。所以为避免名字冲突,经常用大写字母表示。

    #ifndef SELF_H

    #define SELF_H

    //include <else1>

    //include <else2>

    //definition of class,or declaration of  var, fun;

    #endif

    在源文件中#include接收以下2种形式:

    #include <standardheader>

    #include "selfdefinition.h"

    举例:有三个文件:test.h;fun1.cpp;main.cpp;main 要调用 fun1中的add_attri().

    test.h内容:

    #ifndef FUN_H
    #define FUN_H


    #include "fstream"
    #include <vector>
    #include <iostream>
    #include <string>

    int add_attri();

    #endif

    fun1.cpp的内容:

    #include "test.h"

    int add_attri()

    {//.....

      return 0;

    }

    main.cpp内容:

    #include "test.h"

    int main()

    {

      add_attri();

      return 0;

    }

    http://zhidao.baidu.com/link?url=S8nuTKhCvq0yGvTmQEqiQ_lfRecKzceFa-u30-PrZUT4TAczNsvLhRZ0tf0I1J-ZFh5lm7ieLvGtiWAkvJj14Y0Vl_O3qLBE_Zt_aCgFQBm

  • 相关阅读:
    hdu 5053 the Sum of Cube
    [LeetCode] Word Pattern
    [LeetCode] Minimum Depth of Binary Tree
    [C++] std::vector
    [LeetCode] Count Binary Substrings
    [LeetCode] Degree of an Array
    [LeetCode] String to Integer (atoi)
    [LintCode] 比较字符串
    [LeetCode] Valid Parentheses
    [LeetCode] Perfect Number
  • 原文地址:https://www.cnblogs.com/xaf-dfg/p/3394404.html
Copyright © 2011-2022 走看看