• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
返回主页

独立特行

生活不止眼前的苟且,还有油条和豆浆^_^

  • 博客园
  • 首页
  • 新随笔
  • 管理

Cxx中括号操作符的重载举例及解析


C++项目中,经常会遇到使用重载()操作符的地方,请看下面一个例子:
 
view plain
#include <iostream>  
using namespace std;  
class Clastype  
{  
    public:  
        Clastype(int a)  
        {  
            cout << "Hello Clastype!" << a << endl;  
        }  
        bool operator ()(int b)  
        {  
            cout << "Hello Clastype()!" << b << endl;  
            return true;  
        }  
};  
int main()  
{  
    Clastype a(1);  
    Clastype(2);  
    Clastype t = Clastype(3);  
    t(4);  
    Clastype *b = new Clastype(5);  
    (*b)(6);  
}  
 
运行结果如下:

view plain
@-desktop:~/test$ g++ -o o 6.cpp  
@-desktop:~/test$ ./o  
Hello Clastype!1  
Hello Clastype!2  
Hello Clastype!3  
Hello Clastype()!4  
Hello Clastype!5  
Hello Clastype()!6  
可见,括号操作符的使用为对象加上
()操作符。类名直接加()操作符为对象的创建。

posted @ 2017-09-30 21:58  Mr.R123  阅读(230)  评论(0)    收藏  举报
刷新页面返回顶部

公告

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3