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