有人可以解释以下语法差异如何改变运算符的工作方式吗?
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)
,是参数列表。
这个接受两个type
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
这个接受一个类型
,并返回对T
的引用。可用于所有实例,const 或非常量。根据返回的引用所指的内容,它可能会破坏 const
允许您通过 const 方法修改内部数据的一致性:
T & operator()(type one) const
最后一个和上面的一样工作,除了不能调用 return 所指的任何非 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!
关于c++ - 运算符重载语法说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15084501/