簡體   English   中英

以下兩個之間有什么區別嗎?

[英]Is there any difference between the following two?

我為+重載定義了一個全局非成員方法

喜歡

ClassA operator+(const ClassA& a, const ClassB& b);
{
   blah blah ;
}

在交際中,我可以使用

1)

ClassA operator+(const ClassB& b, const ClassA& a)
{
      return operator+(a,b);
}

2)

ClassA operator+(const ClassB& b, const ClassA& a)
{
       return a + b;
}

1和2之間有什么區別?

除了@barakmanos在評論中首先指出的明顯差異(“第二個更具可讀性”),還有另一個技術差異。

假設一秒鍾,以下定義:

struct B;

struct A
{
    void operator+(B const&) const { ::std::cout << "member\n"; }
    friend void operator+(A const&, B const&) { ::std::cout << "friend\n"; }
};

struct B { };

現在,考慮以下三個陳述:

    operator+(A(), B());
    A().operator+(B());
    A() + B();

第一個顯然是調用朋友(免費)功能,第二個調用成員。 但是,如果另一個沒有定義,第三個將調用。 在這種特殊情況下,它找不到更好的匹配,因此會形成錯誤。 有幾種方法可以修改此行為,例如,如果const -requirements中的成員函數不同,則表達式可能是正確的,只會導致更大的重載集。

這表明了兩個表達式的不同之處: operator+(a,b) 考慮自由函數而不是重載二元加運算符的成員函數。

事實上,C ++標准有另一個例子:

A() + B() 執行與參數相關的查找,而operator+(A(), B())執行常規函數查找。 這意味着以下是一個錯誤(取自C ++11§13.3.1.2.10):

struct A { };
void operator + (A, A);
struct B {
    void operator + (B);
    void f ();
};
A a;
void B::f() {
    operator+ (a,a); // error: global operator hidden by member
    a + a; // OK: calls global operator+
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM