类的用户接口是指使用这个类的程序员所能访问得到的接口。典型的接口里只有函数存在,因为在用户接口里放上数据成员会有很多缺点。应该把哪些函数放到接口里面呢?
原则:接口完整且最小。
所谓完整就是使用户能完成所有合理的功能,意即合理的任务有合理的方法。最小就是函数尽量少,两个函数之间没有功能覆盖。函数太多的接口有三点:
(1)函数多,类的可读性就越差。难于学习、维护。
(2)为系统增加开销。
例1.
template
class array
{
public:
enum boundscheckingstatus {no_check_bounds = 0,
check_bounds = 1};
array(int lowbound, int highbound,
boundscheckingstatus check = no_check_bounds); //构造函数
array(const array& rhs); //拷贝构造函数
~array(); //析构函数
array& operator=(const array& rhs); //赋值函数
private:
int lbound, hbound; // 下限, 上限
vector
data; // 数组内容; 关于vector,
boundscheckingstatus checkingbounds;
};
如果你想为类加上
array(int size,boundscheckingstatus check = no_check_bounds);构造函数,那么接口就不是最小,因为这个构造函数完全可以用
array(int lowbound, int highbound,
boundscheckingstatus check = no_check_bounds)实现。 那么上面的类定义是完整的吗?不是,因为有些功能类还没有实现。还应该有一个数组的索引函数。
// 返回可以读/写的元素
t& operator[](int index);
// 返回只读元素
const t& operator[](int index) const;
通过两次声明同一个函数,一次带const一次没有const,就提供了对const和非const array对象的支持。这还不是最小的类,还得提供返回数组上下限的函数。
int lowbound() const;
int highbound() const;