运算符重载语法说明



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

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

假设它们都是成员,则所有成员都按值接受一个type对象。这意味着,至少在语义上,主体操作符有自己的type对象副本。operator()语法表示实例是可调用的。在operator()(例如(type a, type b)(之后的是参数列表。

这一个使用两个typetype,并返回对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

此版本需要两个type,并返回一个指向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!

最新更新