c++ - 运算符重载语法说明

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

最佳答案

假设它们都是成员,它们都按值获取一个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

这个接受一个类型,并返回对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/

相关文章:

c++ - 检查字符串的长度

C++ - 精确时间 vector

C++ 指针 GUI QT

c++ - 为什么在这种情况下转发引用不起作用?

c++ - Bool 运算符重载不起作用

c++ - C++中的运算符重载

c++ - 下次使用该功能时,计数器会被窃听

c++ - Winapi shell 扩展覆盖 Windows 命令

c++ - 模板上的重载算术运算符导致 Unresolved external 错误

c++ - 在重载中返回 const 元素