运算符重载语法澄清

时间:2013-02-26 08:29:04

标签: 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

1 个答案:

答案 0 :(得分:5)

假设他们都是成员,他们都按价值获取type个对象。这意味着,至少在语义上,主体操作符具有自己的type对象副本。 operator()语法意味着实例可以调用。在operator()之后的内容,例如(type a, type b),是参数列表。

这一个需要两个type s 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

此版本需要两个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。根据返回的引用所引用的内容,它可能会破坏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!
相关问题