1

有人可以解释以下语法差异如何改变运算符的工作方式吗?

T & operator()(type one, type two)
const T * operator()(type one, type two)
T & operator()(type one) const
const T & operator()(type one) const
4

1 回答 1

5

假设它们都是成员,它们都type按值获取对象。这意味着,至少在语义上,body 操作符拥有自己的type对象副本。operator()语法意味着实例是可调用的。后面的operator(),例如(type a, type b),是参数列表。

这个需要两个types type,并返回对 的引用T。不能在const实例上使用。

T & operator()(type one, type two)

可以这样称呼它:

MyFunctor x;
type a, b;
T& r = x(a,b); // take reference
T c = x(a,b);  // make copy from reference. Assumes T has copy constructor

这个版本需要两个types,并返回一个指向 的指针const T。不能在const实例上使用。T不能调用非常量方法。

const T * operator()(type one, type two)

例子:

MyFunctor x;
type a, b;
const T* p1 = x(a,b); // pointer to const
T* p2 = x(a,b);       // Error! Must have const T* on LHS

这个接受一个type,并返回一个对T. 可用于所有实例,常量或非常量。根据返回的引用所指的内容,它可能会破坏const允许您通过 const 方法修改内部数据的一致性:

T & operator()(type one) const

最后一个与上面的一样工作,除了不能const调用返回所指的任何非方法。

const T & operator()(type one) const

MyFunctor x;
type a;
const T& r = x(a); // take reference to const
T c = x(a);        // make copy from reference. Assumes T has copy constructor
T& r = x(a);       // Error! Cannot take reference to non-const!
于 2013-02-26T08:34:55.790 回答