成员函数和使用类型别名来简化类

成员函数

在类外部定义的成员函数必须指明它们是在类的作用域中。

Sales_item::avg_price 的定义使用作用域操作符来指明这是Sales_item 类中 avg_price 函数的定义。

在类内部,声明成员函数是必需的,而定义成员函数则是可选的。在类内部定义的函数默认为 inline。

在类外部定义的成员函数必须指明它们是在类的作用域中。Sales_item::avg_price 的定义使用作用域操作符来指明这是Sales_item 类中 avg_price 函数的定义。

将关键字 const 加在形参表之后,就可以将成员函数声明为常量:

double avg_price() const;

const 成员不能改变其所操作的对象的数据成员。const 必须同时出现在声明和定义中,若只出现在其中一处,就会出现一个编译时错误。

使用类型别名来简化类

例如, 可以定义一个名为 Screen 的类型表示计算机上的窗口。 每个 Screen可以有一个保存窗口内容的 string 成员, 以及三个 string::size_type 成员:一个指定光标当前停留的字符,另外两个指定窗口的高度和宽度。可以用如下方式这个类的成员:

class Screen {
public:
// interface member functions
private:
std::string contents;
std::string::size_type cursor;
std::string::size_type height, width;
};

除了定义数据和函数成员之外,类还可以定义自己的局部类型名字。如果为std::string::size_type 提供一个类型别名,那么 Screen 类将是一个更好的抽象:

class Screen {
public:
// interface member functions
typedef std::string::size_type index;
private:
std::string contents;
index cursor;
index height, width;
};

 

posted @ 2018-05-05 22:17  刘-皇叔  阅读(480)  评论(0)    收藏  举报