当我在 operator overloading 上查找书籍和堆栈溢出文章时,我发现了以下内容:
When an overloaded operator is a member function, this is bound to the left-hand operand. Member operator functions have one less (explicit) parameter than the number of operands.
(Addison Wesley,C++ 入门)
所以我的问题是,由于 *
(取消引用)运算符没有任何左操作数,它如何获取其参数(即对象本身或 this
)?
最佳答案
对于所有前缀一元运算符,它对其后面的操作数进行操作。
As an added question would there be any difference in how the overloaded * operator is used if it is defined as a non-member function vs a member function
在大多数情况下,不,除了非成员函数不能访问那个类的私有(private)成员,如果成员函数和非成员函数都存在,编译器需要使用overload resolution。选择更高等级的函数,如果没有更好的函数,这是模棱两可的调用,参见ADL
可靠来源可以看operator overloading ,或者更好的是,标准 C++ 中的第 13.5.1 节 [over.unary]:
A prefix unary operator shall be implemented by a non-static member function (9.3) with no parameters or a non-member function with one parameter. Thus, for any prefix unary operator @, @x can be interpreted as either x.operator@() or operator@(x). If both forms of the operator function have been declared, the rules in 13.3.1.2 determine which, if any, interpretation is used. See 13.5.7 for an explanation of the postfix unary operators ++ and --. 2 The unary and binary forms of the same operator are considered to have the same name. [ Note: Consequently, a unary operator can hide a binary operator from an enclosing scope, and vice versa. —end note ]
同时存在成员(member)和非成员(member)时的选择见13.3.1.2 [over.match.oper]
关于c++ - 当重载为类的成员函数时,取消引用运算符 (*) 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40371000/