简体   繁体   English

如何在 C++ 中正确定义一元运算符

[英]How to define correctly unary operator- in C++

Suppose we have this class definition:假设我们有这个类定义:

class A{
public:
    int a;
    A(int i): a(i){}
    A operator-() const { return A(- a); }     # first operator- function
};
A operator-(const A& o) { return A(- o.a); }   # second operator- function

Now, in the main function, if I write:现在,在main函数中,如果我写:

A a1(10);
A a2 = -a1;                # Here the first operator- function (method) is called!

However, if I remove the first definition of operator- in the class, the second function is called.但是,如果我删除类中 operator- 的第一个定义,则会调用第二个函数。 I would llike to know why the compiler prefers the first definition when both of them are provided.我想知道为什么编译器在提供这两个定义时更喜欢第一个定义。

I would like to know also why the compiler accept to call the first function (method).我也想知道为什么编译器接受调用第一个函数(方法)。 Because I think that the method is synonym to a1- and not -a1 : The object on which the method is applied comes before (at the left of) the operator.因为我认为该方法是a1-而不是-a1同义词:应用该方法的对象出现在运算符之前(左侧)。

From the C++ standard , unary minus operator shall be defined like this:根据 C++ 标准,一元减运算符应定义如下:

T T::operator-() const;

inside class definition, and like this:在类定义中,像这样:

T operator-(const T &a);

outside class definition.外部类定义。

Now, you have both definition types in your class, so there member lookup comes in a play as specified here :现在,您的类中有两种定义类型,因此成员查找会按照 此处指定的方式进行:

two separate lookups are performed: for the non-member operator overloads and for the member operator overloads (for the operators where both forms are permitted).执行两个单独的查找:对于非成员运算符重载和成员运算符重载(对于允许两种形式的运算符)。 Those sets are then merged with the built-in operator overloads on equal grounds as described in overload resolution.然后,如重载解析中所述,这些集合与内置运算符重载以相同的理由合并。 If explicit function call syntax is used, regular unqualified name lookup is performed如果使用显式函数调用语法,则执行常规的非限定名称查找

So, basically, member lookup finds A operator-() const;所以,基本上,成员查找找到A operator-() const; , non-member lookup finds A operator-(const A& o); , 非成员查找发现A operator-(const A& o); . . Overload resolution selects A operator-() const;重载解析选择A operator-() const; . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM