簡體   English   中英

如何在構造函數中為具有同名成員的 Object 限定類型名稱?

[英]How do you Qualify a Type Name in a Constructor for an Object which has a Member of the Same Name?

假設我有以下 2 個結構。

struct ErrorCodes
{
    const unsigned long UsbErrorCode
    const DWORD DriverErrorCode;

    ErrorCodes(const unsigned long usbErrorCode, const DWORD driverErrorCode)
        : UsbErrorCode(usbErrorCode),
        WinDriverErrorCode(winDriverErrorCode)
    {
    }
}

struct Response
{
    const char* Message;
    const ErrorCodes ErrorCodes;

    Response(const char* message, const ErrorCodes errorCodes)
        : Message(message),
        ErrorCodes(errorCodes)
    {
    }
}

如何在Response的構造函數中限定const ErrorCodes ,以便編譯器知道我指的是類型ErrorCodes而不是成員ErrorCodes 我不想更改名稱,因為這需要映射到 C# 結構以進行互操作。

我目前得到的編譯器錯誤是: member "Response::ErrorCodes" is not a type name

只需將::添加到ErrorCodes類型(如果它在全局命名空間中)或ns:: (如果它在命名空間ns或您想要的任何名稱中)。 ::ErrorCodes 正如@goodvibration 在評論中提到的那樣,最好避免這種名稱沖突。

const ::ErrorCodes ErrorCodes;

::是 scope 分辨率運算符。

您可以重命名類型。 或者將其移動到單獨的命名空間中。

namespace ns {
struct ErrorCodes
{
    const unsigned long UsbErrorCode;
    const int DriverErrorCode;

    ErrorCodes(const unsigned long usbErrorCode, const int driverErrorCode)
        : UsbErrorCode(usbErrorCode),
        DriverErrorCode(driverErrorCode)
    {
    }
};
}

struct Response
{
    const char* Message;
    const ns::ErrorCodes ErrorCodes;

    Response(const char* message, const ns::ErrorCodes errorCodes)
        : Message(message),
        ErrorCodes(errorCodes)
    {
    }
};

暫無
暫無

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

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