C++系列之:如何编写并使用一个类

来源:互联网 发布:win7无法解析域名 编辑:程序博客网 时间:2024/04/29 17:43

 

(By LPQ 2007-05-23 09:27:30)

编写并使用一个类最少要有三个文件:规格说明文件(specification file)、实现文件(imlementation file)、客户代码(client code)。下面以C++ Builder 6为例讲解如何编写并使用一个类,其它开发工具如VC等与此过程类似。

1、用向导生成控制台应用程序框架。file->new->other->new->console wizard。注意在选择“source type”时按如下图示进行勾选。

C++系列之:如何编写并使用一个类

2、用向导生成控制台应用程序框架后,对工程(A project is a collection of files that make up an application or dynamic-link library. Some of these files are created at design time. Others are generated when you compile the project source code. )进行保存:file->save all。保存时有两个文件,一个是unitX.cpp(C++源代码),一个projectX.bpr(工程文件,记录工程中有哪些文件,编译选项等,此文件由C++ Builder生成、管理。程序编译完后,可执行文件的名字与工程文件名同),保存时要保存到恰当的、存取方便的文件夹中;如果需要可以给要保存的两个文件换成别的名字

3、用向导生成类的头文件:file->new->other->new->head file。编写头文件并存盘,可以根据需要对此头文件进行改名。此处以Time.h为例。存盘时下面的代码存为time.h。注意如果用到了预定义的类,需要包含相关的头文件。例如如果有一个数据成员是string类型的,则头文开始处应该有:#include <string>与using namespaces std

// Specification file (Time.h)

class Time // Declares a class data type

{ // does not allocate memory

public : // Five public function members

void Set (int hours , int mins , int secs);

void Increment ();

void Write () const;

bool Equal (Time otherTime) const;

bool LessThan (Time otherTime) const;

private : // Three private data members

int hrs;

int mins;

int secs;

};

4、用向导生成类的实现文件:file->new->other->new->Cpp file。编写实现文件并存盘,可以根据需要对此头文件进行改名。以下以Time.cpp为例。存盘时下面的代码存为time.cpp。下面代码有所节略。

// Implementation file “time.cpp”

// Implements the Time member functions.

#include “ time.h” // Also must appear in client code

#include <iostream>

. . .

bool Time::Equal( Time otherTime) const

// Postcondition: Return value == true,

// if this time equals otherTime,

// otherwise == false

{

return ((hrs == otherTime.hrs)

&& (mins == otherTime.mins)

&& (secs == otherTime.secs));

}

. . .

5、编写客户代码。这里在main函数中对编写的类进行测试。首先在main函数所在文件开始处#include "time.h",再按如下方式使用Time类。

#inlcude <Time.h>

...

Time t1; //定义对象

t1.set(10, 20,30);//调用公有函数

...

6、编译工程,并执行程序。

注:在"命令提示符窗口"执行程序的方法:开始->运行在输入框中输入"CMD",回车。进入命令提示符窗口。使用CD命令切换到程序所在目录并执行编译出来的后缀是exe的程序。

原创粉丝点击