簡體   English   中英

如何在以下c ++代碼中基於返回類型進行運算符重載解析

[英]how does operator overload resolution work based on return type in the following code of c++

我知道在C ++中沒有基於返回類型的合法重載; 即您不能做類似的事情:

int operator ++ getOwner();
char operator ++ getOwner();

但是,我偶然發現了以下內容:

https://stackoverflow.com/a/9569120/1376317

class Proxy
{
    My const* myOwner;
public:
    Proxy( My const* owner ) : myOwner( owner ) {}
    operator int() const
    {
        return myOwner->getInt();
    }
    operator char() const
    {
        return myOwner->getChar();
    }
};

我的問題是在這種配置下操作員重載如何工作。 您如何在main.cpp中調用它來獲得這種重載。 編譯器如何演繹,如何調用正確的重載?

我的問題是在這種配置下操作員重載如何工作。

這些運算符提供隱式轉換 這意味着該類可以在需要intchar許多上下文中使用,並將使用這些運算符提供期望的值。

您如何在main.cpp中調用它來獲得這種重載。

以下是一些隱式轉換的示例:

Proxy p = whatever();
int i = p;   // convert to int
char c = p;  // convert to char
long l = p;  // ERROR: ambiguous

void f(int);
f(p);        // convert to int

void g(int);
void g(char);
g(p);        // ERROR: ambiguous

您還可以使用通常的轉換符號請求顯式轉換:

long l = static_cast<int>(p);  // convert to int, then to long
g((char)p);                    // convert to char

編譯器如何演繹,如何調用正確的重載?

只要類型不匹配,編譯器就會尋找轉換序列。 規則很復雜,但是基本上,該序列最多可以包含一個用戶定義的轉換 (使用這樣的運算符或轉換構造),以及標准轉換,例如intlong

有時稱為“ 返回類型解析器”慣用語或“返回類型超載”。 由於需要隱式轉換(例如,基於要初始化或分配給的對象的類型)的使用上下文,因此選擇了要調用的轉換運算符。 例如:

#include <stdio.h>

class RtR {
public:
    operator int() const
    {
        puts("operator int()");
        return 42;
    }
    operator double() const
    {
        puts("operator double()");
        return 3.14;
    }
};

void f(int) {}

int main()
{
    RtR x;
    int i = x; // or int i = RtR();
    double d = x;
    f(x);
}

輸出:

operator int()
operator double()
operator int()

現場觀看

在13.1可重載聲明中:

只能重載返回類型不同的函數聲明。 [注意:...不適用於因名稱查找(例如,由於使用指令)或重載解析(例如,用於操作員功能)而構造的功能集...]

因此,這是有效的:

struct X {
    // Conversion function:
    operator int () { return 1; }
    operator double () { return 2; }
};

另外(與問題無直接關系):

struct Y
{
    // Operator (Function call):
    int operator () (int) { return 1; }
    double operator () (double) { return 2; }

    // Operator (Subscripting):
    int operator [] (int) { return 1; }
    double operator [] (double) { return 2; }

    // Operator (Shift):
    int operator << (int) { return 1; }
    double operator << (double) { return 2; }

    // and more ...
};

上面的代碼用於operator類型轉換,並提供了一種隱式方式將Proxy類型轉換為intchar

編譯器根據轉換調用的上下文“知道”,例如:

Proxy p;

// p_int will be set equal to p.my_owner->getInt()
int p_int = p;

// p_char will be set equal to p.my_owner->getChar()
char p_char = p;

它是代理的事實無關緊要; 相同的東西適用於任何班級。 這些是轉換運算符,編譯器根據調用代碼中的用法選擇正確的版本。

struct S {
    operator int() const { return 1; }
    operator double() const { return 2.0; }
};

int main() {
    S s;
    int i = s;
    double d = s;
    std::cout << i << ' ' << d << '\n';
    return 0;
}

暫無
暫無

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

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