2016-05-30 44 views
1

我试图将main中声明的变量传递给我的类的私有变量,而不传递它作为构造函数的参数。我需要将中断控制器连接到多个硬件中断,而无需重新初始化中断实例并覆盖它。C++将外部变量导入私有类变量

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

而类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); 
}; 

的设备ID和slaveMask在其中包括的报头定义。

有没有办法实现这个?

+0

所以,你必须XScuGic'的'两个实例;一个全局变量和一个作为'Foo'中的私有成员?你想要一个副本在私人成员?你可以有一个私人的参考成员。 – wally

+0

你为什么不在你的课堂上储存'refference'或'pointer'? –

+0

@flatmouse是的,我想要同样的中断实例也可以在我的班级没有明确传递 – Etruscian

回答

0

可以初始化一个私有的类基准构件与使用全局变量的构造函数,所以后来就没有必要将它传递在构造函数中:

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