设为首页 加入收藏

TOP

[C/C++]_[操作符重载operator type()和operator()的区别]
2015-07-20 17:47:55 来源: 作者: 【 】 浏览:3
Tags:C/C 操作 重载 operator type 区别


场景:

1.看到WTL的CWindow源码时会发现这样的operator重载,仔细看会发现它并不是重载()操作符.

	operator HWND() const throw()
	{
		return m_hWnd;
	}

如果重载()操作符,应该是,返回值HWND应该在operator的左边,而且应该有两个括号()

HWND operator ()() const throw()
{
	return m_hWnd;
}

这种类型的操作符重载应该是type conversion operator(类型转换操作符),它可以把类类型转换为指定的类型,如果定义了这种转换,好处就是该类对象赋值给 method(HWND),参数是HWND类型的方法时会自动转换为HWND类型,或者需要打印这个类信息时。operator std::string().


函数原型:

operator Type()

而重载()操作符确实是需要调用()才会调用,比如object([param])。

测试代码:

#include 
  
   
#include 
   
     #include 
    
      #include 
     
       #include 
      
        using namespace std; class Total { public: Total(float sum,float discount) { sum_ = sum; discount_ = discount; } ~Total(){} operator float() { return sum_* discount_; } operator std::string() { char str[128]; sprintf(str,"%f",sum_* discount_); return std::string(str); } float operator()() { return sum_* discount_; } float sum_; float discount_; }; int main(int argc, char const *argv[]) { Total to(89,0.8); cout << to << endl; cout << to() << endl; cout << (std::string)to << endl; //cout << to(0.9) << endl; return 0; } 
      
     
    
   
  

输出:

71.2
71.2
71.200001


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇HDU1575-Tr A(矩阵快速幂) 下一篇hdu 4267 A Simple Problem with ..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·如何利用Python做数 (2025-12-24 23:48:36)
·如何使用python进行 (2025-12-24 23:48:34)
·python 爬虫入门该怎 (2025-12-24 23:48:31)
·Java 实现多个大文件 (2025-12-24 23:22:00)
·Java多线程编程在工 (2025-12-24 23:21:56)