初探运算符重载------小括号

在c/c++中。”()”操作符表示的是一个函数调用符号,同样,它只能够通过类的成员函数来重载:

 1 #include <iostream>
 2 class cls
 3 {
 4 public:
 5     cls()
 6     {
 7         printf("构造函数\n");
 8     }
 9     void operator() ()  //重载"()"操作符,"()"内无操作数
10     {
11         printf("HelloWorld!\n");
12     }
13 
14     void operator() (const char* str) //重载"()","()"内的操作数是字符串
15     {
16         printf("%s", str);
17     }
18 };
19 
20 int main(void)
21 {
22     cls cc;
23     cc();
24     cc("Hello Linux\n");
25     //system("pause");
26     return 0;
27 }
输出结果:
    构造函数
    HelloWorld!
    Hello Linux

猜你喜欢

转载自www.cnblogs.com/wangbin-heng/p/9657662.html
今日推荐