喜欢这本书的风格,以应用程序为例,来让大家学习Qt。在4.5节中是以spreadsheet为例。
在spreadsheet.h中SpreadsheetCompare类是这样定义的。
点击(此处)折叠或打开
- class SpreadsheetCompare
- {
- public:
- bool operator()(const QStringList &row1,
- const QStringList &row2) const;
- enum { KeyCount = 3 };
- int keys[KeyCount];
- bool ascending[KeyCount];
- };
另外在spreadsheet.cpp中对SpreadsheetCompare类的“()”符号进行了重载。这样就允许把这个类像函数一样使用。把这样的类称为函数对象,或者称为仿函数。
点击(此处)折叠或打开
- bool SpreadsheetCompare::operator()(const QStringList &row1,
- const QStringList &row2) const
- {
- for (int i = 0; i < KeyCount; ++i) {
- int column = keys[i];
- if (column != -1) {
- if (row1[column] != row2[column]) {
- if (ascending[i]) {
- return row1[column] < row2[column];
- } else {
- return row1[column] > row2[column];
- }
- }
- }
- }
- return false;
- }
这样就可以像下面这样使用:
点击(此处)折叠或打开
- QStringList row1, row2;
- SpreadsheetCompare compare;
- ...
- if (compare(row1, row2)) {
- //row1 is less than row2
- }
4.5节里还举了这样一个简单的例子。
点击(此处)折叠或打开
- class Square
- {
- public:
- int operator()(int x) const { return x * x; }
- }
点击(此处)折叠或打开
- Square square;
- int y = square(5);
- //y equals 25