C++中的头文件(.h)和源文件(.cc)

头文件(,h):

写类的声明(包括类里面的成员和方法的声明)、函数原型、#define常数等,但一般来说不写出具体实现。

在写头文件时需要注意,在开头和结尾处必须按照如下样式加上预编译语句:

#ifndef HELLO_H
#define HELLO_H

//Your codes

#endif
这样做是为了防止重复编译,不这样做就有可能出错。至于HELLO_H这个名字实际上是无所谓的,叫什么都行,只要符合规范就行。原则上来说,非常建议把它写成这种形式,因为比较容易和头文件的名字对应。


源文件(.cc):

源文件主要写实现头文件中已经声明的那些函数的具体代码。需要注意的是,开头必须#include一下实现的头文件,以及要用到的头文件。那么当需要用到自己写的头文件中的类时,只需要#include进来就行了。


例子:

下面举个最简单的hello的例子描述一下。

第一步,建立一个空工程。

第二步,建立名为Hello.h的头文件,内容如下:

#ifndef HELLO_H
#define HELLO_H

using namespace std;

class Hello
{
private:
        std::string name;
public:
        Hello();
        Hello(std::string name);
        void hello();
};

#endif
第三步,建立名为Hello.cc的头文件,内容如下:

#include <iostream>
#include "Hello.h"

using namespace std;

Hello::Hello()
{
        this->name = "Tom";
}

Hello::Hello(std::string name)
{
        this->name = name;
}

void Hello::hello()
{
        cout << "Hello " << this->name;
}
第四步,建立一个test.cc来测试Hello类。内容如下:

#include <iostream>
#include "Hello.h"

using namespace std;

int main()
{
    Hello h("Jerry");
    h.hello();
    return 1;
}

#include <assert h>     设定插入点 #include <ctype h>     字符处理 #include <errno h>     定义错误码 #include <float h>     浮点数处理 #include <fstream h>    文件输入/输出 #include <iomanip h>    参数化输入/输出 #include <iostream h>    数据流输入/输出 #include <limits h>     定义各种数据类型最值常量 #include <locale h>     定义本地化函数 #include <math h>      定义数学函数 #include <stdio h>     定义输入/输出函数 #include <stdlib h>     定义杂项函数及内存分配函数 #include <string h>     字符串处理 #include <strstrea h>    基于数组的输入/输出 #include <time h>      定义关于时间的函数 #include <wchar h>     宽字符处理及输入/输出 #include <wctype h>     宽字符分类 int spawnvpe int mode char pathname char argv[] char envp[] spawn函数族在mode模式下运行子程序pathname 并将参数 arg0 arg1 arg2 argv[] envp[] 传递给子程序 出错返回 1 mode为运行模式 mode为 P WAIT 表示在子程序运行完后返回本程序 P NOWAIT 表示在子程序运行时同时运行本程序 不可用 P OVERLAY表示在本程序退出后运行子程序 在spawn函数族中 后缀l v p e添加到spawn后 所指定的函数将具有某种操作能力 有后缀 p时 函数利用DOS的PATH查找子程序文件 l时 函数传递的参数个数固定 v时 函数传递的参数个数不固定 ">#include <assert h>     设定插入点 #include <ctype h>     字符处理 #include <errno h>     定义错误码 #include <float h>     浮点数处理 #include <fstream h>    文件输入/输出 #include <iomanip h& [更多]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值