簡體   English   中英

C ++在主函數中初始化靜態變量

[英]C++ initialise static variable in main function

// I need to have access to 'a' in whole file
// I cannot call constructor now
static A a;

int main()
{
    /*
        some code
    */

    glewInit();

    /*
        some more code
    */

    a = A(); 
}

我需要在調用glewInit()函數后調用構造函數
它的構造函數正在使用gl函數

我可以阻止C ++初始化'a'變量嗎?

將函數與靜態變量一起使用:

A &getA() 
{
    static A a;
    return a;
}

並僅在可以創建它時訪問它。

如果創建僅依賴於全局狀態,那么Slava的答案是很好的,但是如果您需要計算一些構造函數參數,那么最好的辦法是組合一個局部變量(因為它在main() ,它將一直存在到程序結尾)以及指向它的指針:

static A* a;

int main()
{
    /* some code that determines arg1 and arg2 */

    A real_a(arg1, arg2);
    a = &real_a;

    /* call all the functions that use ::a */
}

暫無
暫無

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

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