C++ 将外部变量导入私有 class 变量

C++ import external variable into private class variable

我试图将 main 中声明的变量放入我的 class 的私有变量中,而不将其作为构造函数的参数传递。我需要 link 中断控制器到多个硬件中断而不重新初始化中断实例并因此覆盖它。

XScuGic InterruptInstance;

int main()
{
    // Initialize interrupt by looking up config and initializing with that config
    ConfigPtr = XScuGic_LookupConfig(INTERRUPT_DEVICE_ID);
    XScuGic_CfgInitialize(&InterruptInstance, ConfigPtr, ConfigPtr->BaseAddr);

    Foo foo;
    foo.initializeSpi(deviceID,slaveMask);

    return 0;
}

并执行 class Foo:

class Foo
{
     // This should be linked to the one in the main
     XScuGic InterruptInstance;
public:
     // In here, the interrupt is linked to the SPI device
     void initializeSpi(uint16_t deviceID, uint32_t slaveMask); 
};

deviceID 和 slaveMask 在包含的 header 中定义。

有什么方法可以实现吗?

您可以使用使用全局变量的构造函数初始化私有 class 引用成员,这样就不需要在构造函数中传递它了:

XScuGic InterruptInstance_g; // global variable

class Foo {
private:
    const XScuGic& InterruptInstance; // This should be linked to the one in the main
public:
    Foo() : InterruptInstance{InterruptInstance_g} {}; // private variable is initialized from global variable
    void initializeSpi(uint16_t deviceID,uint32_t slaveMask); // In here, the interrupt is linked to the SPI device
};

int main()
{
    // Initialize interrupt by looking up config and initializing with that config
    ConfigPtr = XScuGic_LookupConfig(INTERRUPT_DEVICE_ID);
    XScuGic_CfgInitialize(&InterruptInstance,ConfigPtr,ConfigPtr->BaseAddr);

    Foo foo{}; // reference is not required as it will come from the global variable to initialize the private reference member
    foo.initializeSpi(deviceID,slaveMask);

    return 0;
}