1. 程式人生 > >Cxx中括號操作符的重載舉例及解析

Cxx中括號操作符的重載舉例及解析

ray art tor detail cout desktop log ati gree


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 ?
可見,括號操作符的使用為對象加上
()操作符。類名直接加()操作符為對象的創建。

Cxx中括號操作符的重載舉例及解析