运算符重载语法澄清

Ash*_*man 1 c++ operator-overloading

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

T & operator()(type one, type two)
const T * operator()(type one, type two)
T & operator()(type one) const
const T & operator()(type one) const
Run Code Online (Sandbox Code Playgroud)

jua*_*nza 5

假设它们都是成员,它们都type按值获取对象.这意味着,至少从语义上讲,body操作符有自己的type对象副本.该operator()语法意味着实例是调用.接下来的内容operator(),例如(type a, type b)参数列表.

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

T & operator()(type one, type two)
Run Code Online (Sandbox Code Playgroud)

它可以被称为这样的东西:

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
Run Code Online (Sandbox Code Playgroud)

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

const T * operator()(type one, type two)
Run Code Online (Sandbox Code Playgroud)

例:

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
Run Code Online (Sandbox Code Playgroud)

这个只需一个type,并返回一个引用T.可以在所有实例上使用,const或非const.根据返回的引用所引用的内容,它可能会破坏const一致性,允许您通过const方法修改内部数据:

T & operator()(type one) const
Run Code Online (Sandbox Code Playgroud)

最后一个工作如上所述,除了不能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!
Run Code Online (Sandbox Code Playgroud)