vc多文件创建方法的学习笔记

来源:互联网 发布:手机淘宝哪里看追评 编辑:程序博客网 时间:2024/06/10 09:27

            在大概一个月以前我写的程序大都是单文件的程序,而且在学校老师老师也是以单文件程序来交的,而我们在以后的工作中要面临的是多文件程序的创建,那么下面就一个C++程序,在vc6.0环境下为例来说如何创建一个多文件的程序。

         现有一个程序代码如下:

class animal
{
public:
   animal()

 {
 cout<<"ainmal construct"<<endl;
}

 void eat();

 void sleep();

   virtual void breathe();
};

void animal::eat()
{
 cout<<"animal eat!"<<endl;
}


void animal::sleep()
{
 cout<<"animal sleep"<<endl;
}

void animal::breathe()
{
 cout<<"animal breathe!"<<endl;
}

 

class fish : public animal
{
public:
 fish()

{
 cout<<"fish construct"<<endl;
}

 void breathe();
 
 void sleep();

 void eat();
};

void fish::eat()
{
 cout<<"fish eat"<<endl;
}

void fish::sleep()
{
 cout<<"fish sleep"<<endl;
}

void fish::breathe()
{
 cout<<"fish breathe"<<endl;
}

 

void fn(animal *pan)
{
 pan->breathe();
}


int main()
{
 fish fh;
 animal *pan;
 pan=&fh;
 pan->breathe();

 return 0;
}

在这个程序代码中,我们现在相应的项目文件的目录下创建四个文件,分别命名为animal.h,animal.cpp,fish.h,fish.cpp,然后在vc中将这些文件添加大工程中。在animal.h文件中的代码为:

#ifndef AMIMAL_H_H
#define AMIMAL_H_H
class animal
{
public:
 animal();

 void eat();

 void sleep();

    virtual void breathe();
};
#endif

即头文件中只写程序的声明,这里的预编译命令是为了解决在主函数调用时,头文件重复被调用出错。在animal.cpp文件中的代码:

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

animal::animal()
{
 cout<<"ainmal construct"<<endl;
}

void animal::eat()
{
 cout<<"animal eat!"<<endl;
}


void animal::sleep()
{
 cout<<"animal sleep"<<endl;
}

void animal::breathe()
{
 cout<<"animal breathe!"<<endl;
}

相应的fish.h和fish.cpp文件的代码分别为:

#include"animal.h"

#ifndef FISH_H_H
#define FISH_H_H
class fish : public animal
{
public:
 fish();

 void breathe();
 
 void sleep();

 void eat();
};
#endif

#include"animal.h"
#include"fish.h"
#include<iostream.h>

fish::fish():animal()
{
 cout<<"fish construct"<<endl;
}

void fish::eat()
{
 cout<<"fish eat"<<endl;
}

void fish::sleep()
{
 cout<<"fish sleep"<<endl;
}

void fish::breathe()
{
 cout<<"fish breathe"<<endl;
}

这里注意在头文件包含时,该段程序要用相应的头文件时才包含。好了,一个多文件的程序就建立成功了,每个文件编译,链接,执行就可以了。

 

 

原创粉丝点击