本文共 1371 字,大约阅读时间需要 4 分钟。
templateoutput:class binFun {public: virtual void operator() (T a, T b) { cout << "base\n"; }};template class Greater:public binFun {public: void operator() (T a, T b) { cout << "greater\n"; }};template class Less:public binFun {public: void operator() (T a, T b) { cout << "less\n"; }};int main(int argc, char *argv[]) { binFun *bin = new Greater (); bin->operator ()(5,2); (*bin)(5,2); Greater gt; gt(5,2); binFun &b = Greater (); b(5,2); Greater * pgt = new Greater (); (*pgt)(5,2);}
greater
greater
greater
greater
greater
需要注意的三点:
1. 基类函数要加virtual
2. 只有在指针和引用的情况下才能发生多态
3. ()括号的运算符优先级较高,所以指针调用括号运算符时要加括号(*bin)
(5,2) ,保证第一个括号先执行,后一个括号再执行
在c++ stl中的
templatestruct binary_function { typedef Arg1 first_argument_type; typedef Arg2 second_argument_type; typedef Result result_type; };
中没有定义opreator()运算符
但是在其子类greater和less中定义了运算符,为什么要这么设计呢.....
templatestruct greater : binary_function { bool operator() (const T& x, const T& y) const { return x>y;}};
转载地址:http://byeti.baihongyu.com/