图一展示了IntCell类的接口,图二提供了类接口的实现,图三则给出一个用到IntCell的main例程。
#ifndef IntCell_H
#define IntCell_H
/**
* 一个模拟整数单元的类
*/
class IntCell
{
public:
explicit IntCell(int initialValue=0);
int read() const;
void write(int x);
private:
int storedValue;
};
#endif
图1 文件IntCell.h中的IntCell类接口
#include "IntCell.h"
/**
* 用initialValue构建IntCell对象
*/
IntCell::IntCell(int initialValue):storedVvalue{initialValue}
{
}
/**
* 返回所存储的值
*/
int InCell::read() const
{
return storedValue;
}
/**
*存储x
*/
void IntCell::write( int x )
{
storedValue = x;
}
图2 文件IntCell.cpp中的IntCell类实现
#include <iostream>
#include "IntCell.h"
using namespace std;
int main()
{
IntCell m;
m.write(5);
cout<<"Cell contents:"<<m.read()<<endl;
return 0;
}
图3 用到文件TestIntCell.cpp中的IntCell的程序
预处理命令
需要接口的知识的源代码必须要#include这个接口文件。为了防止一个接口可能被读两次,被读入时的每一个头文件都要使用预处理程序定义一个符号。接口文件的ifndef检测这个符号是否是未定义的。若不是,通常跳到#endif
作用域解析运算符
每个成员函数必须与它所在的类关联。与类关联的语法是ClassName::member。符号::称作作用域解析运算符
对象声明同于基本类型(以下是正确的)
IntCell obj1; //零参数构造函数
IntCell obj1{};
IntCell obj2(12);//单参数构造函数
IntCell obj2{12};