如何在具有同名成员的对象的构造函数中限定类型名称?

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

您可以重命名类型。或者将其移至单独的命名空间。

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)
    {
    }
};

只需将 :: 添加到 ErrorCodes 类型(如果它在全局命名空间中)或 ns::(如果它在命名空间 ns 中)或您想要的任何名称。喜欢::ErrorCodes。正如@goodvibration 在评论中提到的,最好避免此类名称冲突。

const ::ErrorCodes ErrorCodes;

:: 是范围解析运算符。