我有一个对象,它有一个数学函数。它似乎是operator()
的完美人选。运算符()在C++
具体来说,它是一种光线,它对球体上的每个(phi,theta)位置都有不同的值。
现在的事情是,当类中,访问灯功能有这个crunky语法:
double operator() (double phi, double theta) { // compute light function return sin(2*t) * cos(p) ; // (really this is implemented as a function pointer, // so the light function can be changed) } void functionThatUsesLightFunction() {double val = (2.0, 4.0) ; // seems bad// Whoops! Doesn't work. double val2 = (*this)(2.0, 4.0) ; // ok double val3 = operator()(2.0, 4.0) ; // no thank you }
但是从类外,它得到这个非常好的语法像
foreach(theta on 0..PI) foreach(phi on 0..2*PI) val += light(theta, phi) ;
你认为我在这里误用了operator()
吗?
你不能定义一个(private?)方法'compute(bla)'并在'operator()'中调用它吗?然后你可以在类内调用'compute'并在外面使用'operator()'。 –
第一种机制不会调用'operator()'。 –
我不是'operator()'的粉丝。 Operator()是一个没有名字的方法:这是皇帝的新方法(就像皇帝的新衣服一样)。 'operator()'看起来就像从外面裸露的一样,看起来和内部一样丑陋。这里完全穿衣的功能有什么问题,例如“照明”? –