2016-03-04 55 views
0

发布代码的背景: PayRoll是类的名称。 personSalary是一个双类型变量,personAge是一个整型变量。给出的代码是按年龄或薪水排列列表。无法解释此C++代码

struct less_than_salary 
    { 
     inline bool operator() (const PayRoll& struct1, const PayRoll& struct2) 
     { 
     return (struct1.personSalary < struct2.personSalary); 
     } 
    }; 

struct less_than_age 
    { 
     inline bool operator() (const PayRoll& struct1, const PayRoll& struct2) 
     { 
     return (struct1.personAge < struct2.personAge); 
     } 
    }; 

我想了解一下这部分给定代码的一些帮助。我试着读结构用于和据我所知,它基本上是作为一个类来操作,并允许您一次处理多种类型的变量。如果我错了,在这种情况下用到的结构究竟是什么? 另外,如果有人解释“inline bool operator()”在做什么,我会很感激,因为我之前从未见过这样的内容,而且通过阅读教科书我无法理解。 谢谢你的帮助!

+1

尝试google搜索 “函子”。 –

+1

你的意思是你不懂操作符重载的概念吗? 'operator()'允许类的一个实例对一个* function-call *操作符做出反应。 – jxh

+0

是的,这是我的问题,我很难理解操作符重载。 – ss1111

回答

1

像这样的结构可以在STL功能sort中使用,该功能在诸如std::list之类的数据结构中是可用的。

#include <list> 
#include <iostream> 

int main() { 
    std::list<int> example = {9,8,7,6,5,4,3,2,1}; 

    struct { 
     bool operator()(const int lhs, const int rhs) { 
      return lhs < rhs; 
     } 
    } compare_list; 

    example.sort(compare_list); 

    for(auto &i : example) { 
     std::cout<<i<<" "; 
    } 
} 

输出:

1 2 3 4 5 6 7 8 9 

要理解这是如何工作的,考虑以下几点:

//.. 
testS(compare_list); 
//.. 

template <typename T> 
void testS(T t) { 
    std::cout<< t(4,5) << "\n"; 
    std::cout<< t(5,4) << "\n"; 
} 

输出将

1 
0 
+0

+1谢谢你的解释!我明白代码现在是如何工作的!我还有一个问题。所以_bool operator()_基本上接受了lhs和rhs,使得它们看起来像是_bool_正确的?否则,你会得到一个错误,说“operator == not defined”? – ss1111

+0

是的,我们的'compar_list'结构实现了'()'运算符。 '()'操作符使得它成为一个函子,这意味着它可以像函数一样被调用。 它需要两个参数并返回_lhs

2

这两个结构都是所谓的“仿函数”的实现。定使用像

PayRoll x; 
PayRoll y 
    // initialise x and y 

less_than_salary f; 

if (f(x,y)) // this calls less_than_salary::operator()(x,y) 
    std::cout << "X has lower salary than Y\n"; 
else 
    std::cout << "X has higher salary than Y\n"; 

此外,给定的PayRoll阵列,也能够

PayRoll a[20]; 

// initialise elements of a 

less_than_salary f; 
std::sort(a, a+20, f); // will sort in order of ascending salary 

std::sort(a, a+20, less_than_salary()); // does same as preceding two lines 

标准集装箱(std::vector<PayRoll>等)也可以使用排序。

less_than_age允许做基本上相同的事情,但使用年龄而不是tnan工资作为排序标准。

这里没有函数重载。这两种结构类型都提供了operator(),但这不是超载。

+0

+1谢谢!你能否详细说明为什么没有函数重载?我还是不太明白,我正在努力学习。 – ss1111

+0

函数重载在同一范围内提供具有相同名称的函数,它们接受不同的参数类型。你正在做的是提供两个结构类型,每个结构类型都有一个'operator()',它们具有相同的参数类型。每个结构类型都是不同的作用域。 – Peter