C++项目中,经常会遇到使用重载()操作符的地方,请看下面一个例子:
- #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);
- }
运行结果如下:
- @-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++代码示例介绍了如何在类中重载括号操作符(),并展示了不同调用方式的效果。解释了类名直接加()操作符表示对象创建,而对象加()操作符则调用了重载后的括号操作符。
378

被折叠的 条评论
为什么被折叠?



