本文共 846 字,大约阅读时间需要 2 分钟。
() 运算符用于函数调用
重载格式 类型 类 :: operator() ( 表达式表 ) ;
例1
设 x 是类 X 的一个对象,则表达式
x ( arg1, arg2, … )
可被解释为
x . operator () (arg1, arg2, … )
案例:
//例2:用重载()运算符实现数学函数的抽象
#include <iostream>
class F
{ public :
double operator ( ) ( double x , double y ) ;
} ;
double F :: operator ( ) ( double x , double y )
{ return x * x + y * y ; }
void main ( )
{
F f ;
f.getA();
cout << f ( 5.2 , 2.5 ) << endl ; // f . operator() (5.2, 2.5)
}
比较普通成员函数
代码如下,具体请看注释:
#includeusing namespace std;class F{public: int operator() (int a, int b) //()运算符重载 { return a * a + b * b; }};class F2{public: int MemFunc(int a, int b) //普通成员函数 { return a * a + b * b; }};//void main(){ F f; f(2, 4); //一般写成这种形式的,不是调用构造函数就是调用operator()函数,即括号运算符重载函数 F2 f2; f2.MemFunc(2, 4); //普通成员函数的调用 // //operator() (int a, int b) cout << "hello..." << endl; system("pause"); return;}
转载地址:http://krzmi.baihongyu.com/