函数调用运算符()可以被重用于类的对象。当重载()时,没有创造一个新的调用函数的方式,相反地,这是创建一个可以传递任意数目参数的运算符函数。
/*** bracke.cpp ***/ #include<iostream> using namespace std; class Distance { private: int feet; int inches; public: Distance() { feet = 0; inches = 0; } Distance(int f,int i) { feet = f; inches = i; } void displayDistance() { cout << "F: " << feet << " I: " << inches << endl; } Distance operator()(int a,int b,int c ) { Distance D; D.feet = a + b + 10; D.inches = b + c + 100; return D; } }; int main() { Distance D1(11,10), D2; cout << "First Distance : "; D1.displayDistance(); cout << "Second Distance : "; D2 = D1(10,10,10); D2.displayDistance(); return 0; }
运行结果:
exbot@ubuntu:~/wangqinghe/C++/20190809$ ./bracket
First Distance : F: 11 I: 10
Second Distance : F: 30 I: 120