C++中括号()操作符的重载举例及解析

来源:互联网 发布:免费实时港股软件 编辑:程序博客网 时间:2024/04/28 03:38

http://blog.csdn.net/yang_lang/article/details/6725041


C++项目中,经常会遇到使用重载()操作符的地方,请看下面一个例子:

 

view plain
  1. #include <iostream>  
  2. using namespace std;  
  3. class Clastype  
  4. {  
  5.     public:  
  6.         Clastype(int a)  
  7.         {  
  8.             cout << "Hello Clastype!" << a << endl;  
  9.         }  
  10.         bool operator ()(int b)  
  11.         {  
  12.             cout << "Hello Clastype()!" << b << endl;  
  13.             return true;  
  14.         }  
  15. };  
  16. int main()  
  17. {  
  18.     Clastype a(1);  
  19.     Clastype(2);  
  20.     Clastype t = Clastype(3);  
  21.     t(4);  
  22.     Clastype *b = new Clastype(5);  
  23.     (*b)(6);  
  24. }  

 

运行结果如下:


view plain
  1. @-desktop:~/test$ g++ -o o 6.cpp  
  2. @-desktop:~/test$ ./o  
  3. Hello Clastype!1  
  4. Hello Clastype!2  
  5. Hello Clastype!3  
  6. Hello Clastype()!4  
  7. Hello Clastype!5  
  8. Hello Clastype()!6  

可见,括号操作符的使用为对象加上()操作符。类名直接加()操作符为对象的创建。


原创粉丝点击