博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
括号运算的多态
阅读量:4153 次
发布时间:2019-05-25

本文共 1371 字,大约阅读时间需要 4 分钟。

template
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);}
output:

greater

greater

greater

greater

greater

需要注意的三点:

1. 基类函数要加virtual

2. 只有在指针和引用的情况下才能发生多态

3. ()括号的运算符优先级较高,所以指针调用括号运算符时要加括号(*bin)

(5,2) ,保证第一个括号先执行,后一个括号再执行

在c++ stl中的

template 
struct binary_function { typedef Arg1 first_argument_type; typedef Arg2 second_argument_type; typedef Result result_type; };

中没有定义opreator()运算符

但是在其子类greater和less中定义了运算符,为什么要这么设计呢.....

template 
struct greater : binary_function
{ bool operator() (const T& x, const T& y) const {
return x>y;}};

转载地址:http://byeti.baihongyu.com/

你可能感兴趣的文章
网站优化之Tomcat启用Gzip压缩
查看>>
Linux下mysql的彻底卸载
查看>>
python爬虫解决极验验证码问题
查看>>
使用JS将table表格导出为excel
查看>>
java调用阿里云短信服务接口
查看>>
idea的个性配置
查看>>
Java获取访问者Ip并限制Ip访问页面
查看>>
Java读取src下配置文件的问题
查看>>
网页加载时waiting(TTFB)时间过长的问题解决
查看>>
Java时间日期相关工具类
查看>>
JS使用OSS上传文件遇到的一些问题
查看>>
个人博客写了两年
查看>>
博客添加评论功能
查看>>
VMware Ubuntu安装教程(详细过程)
查看>>
Java新手的通病
查看>>
Java虚拟机知识汇总,Jvm面试必问
查看>>
LifecycleProcessor not initialized - call ‘refresh‘ before invoking lifecycl
查看>>
js实现选中div内容并复制到剪切板
查看>>
海康威视DS-K1F100-D8E发卡器Java版
查看>>
Java十六进制和byte数组转换
查看>>