2016-05-30 63 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; 
}