C++中括号()操作符的重载举例及解析
2016-01-10 23:39
423 查看
C++项目中,经常会遇到使用重载()操作符的地方,请看下面一个例子:
[cpp] view
plaincopy
#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);
}
运行结果如下:
[cpp] view
plaincopy
@-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
可见,括号操作符的使用为对象加上()操作符。类名直接加()操作符为对象的创建。
[cpp] view
plaincopy
#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);
}
运行结果如下:
[cpp] view
plaincopy
@-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
可见,括号操作符的使用为对象加上()操作符。类名直接加()操作符为对象的创建。
相关文章推荐
- c语言实现数组栈
- Sicily 1198. Substring
- c语言实现双链表
- 一起talk C栗子吧(第九十六回:C语言实例--使用共享内存进行进程间通信二)
- C/C++获取程序执行时间的五个方法对比
- 哈弗曼树讲解---c语言实现
- c语言 c99 标准
- C++学习笔记42——重载操作符之箭头操作符
- POJ 1003 Hangover 水题一道 练习C++编程
- C++编程学习之旅 由浅及深
- 实型常量
- 【C/C++学院】0831-类与对象的异常/面试100题1-100
- C++实现链表基本操作
- C语言快速删除列表选中项算法
- C++中的关键知识点(汇总)
- JAVA使用JNI 调用 C++ DLL 动态连接库从零开始 一
- Sicily 2005. Lovely Number
- c++拾遗-----处理数据
- C语言 关键字、标识符、注释
- 大话设计模式 第二章 策略模式 C++实现