2017-02-17 109 views
0

我正在吐一些舊的C++代碼。 在這裏面,我宣佈一個局部變量是這樣的:C++初始化作爲函數

Pen blackPen(Color(255, 0, 0, 0)); 

這似乎調用構造函數。

我想使這個全局變量,我想在函數中初始化。但是,我無法通過這種方式將變量從初始化中分離出來。當然,我可以定義一個全局變量

Pen blackPen; 

但現在我不知道如何將其初始化:

blackPen = Pen(Color(255, 0, 0, 0)); 

似乎是最合理的,但我得到一個錯誤:

"Gdiplus::Pen::Pen(const Gdiplus::Pen &)" (declared at line 452 of "c:\Program Files (x86)\Windows Kits\8.1\Include\um\gdipluspen.h") is inaccessible

下面的代碼片段顯示了這種行爲:

#include <windows.h> 
#include <gdiplus.h> 
using namespace Gdiplus; 

Pen redPen; 

int main(int argc, char *argv[]) 
{ 
    Pen greenPen(Color(255, 0, 0, 0)); // this initialization works 
    redPen = Pen(Color(255, 0, 0, 0)); // but this doesn't... 
    return 0; 
} 
+1

看來你的拷貝構造函數是私有的。你可以發佈[MCVE](http://stackoverflow.com/help/mcve)嗎? – emlai

+0

看起來你不能。錯誤是說複製構造函數是私有的。它可能是可移動的,你有沒有打開C++ 11? – NathanOliver

+0

請提供[MCVE]。 –

回答

3

I am trying to make this a global variable, which I want to initialize in a function. However, I am not able to split the variable from it's initialization in this way.

一個選項是通過函數提供對變量的訪問。

Pen& getBlackPen() 
{ 
    static Pen pen{Color{255, 0, 0, 0}}; 
    return pen; 
} 

然後,您將有機會獲得隨時隨地對象的函數聲明可用。當第一次調用函數時,它將被初始化。

更新,響應OP的評論

另一種選擇(提供Pen滿足在的std::map值類型的要求):

Pen& getPen(std::string const& name) 
{ 
    static std::map<std::string, Pen> pens = 
    { 
     {"black", Pen{Color{255, 0, 0, 0}} }, 
     {"white", Pen{Color{...}} }, 
     {"red", Pen{Color{...}} }, 
     // etc. 
    }; 
    } 

    return pens[name]; 
} 

現在,你可以使用:

Pen& pen1 = getPen("black"); 
Pen& pen2 = getPen("red"); 
+0

這可行(所以你有我的upvote),但我不覺得它優雅:我不想爲每個筆定義一個函數。我正在等待,如果一個更優雅的解決方案彈出(否則我會接受你的答案)。 – Ruben

+0

更新:當調用GdiShutdown時,這將嘗試銷燬筆,這將導致訪問衝突錯誤。所以它沒有像預期的那樣完全工作。 – Ruben

+1

@Ruben,你提出了有效的分數,但我超出了你原來的職位提出的問題。我希望你能從答案中獲得想法,並使其適應於解決你在程序中看到的所有其他問題。 –

0

我的解決方案是直接定義一個指針而不是Pen,然後使用從畫筆工作的構造函數:

#include <Windows.h> 
#include <gdiplus.h> 
using namespace Gdiplus; 

Brush *blackBrush; 
Pen *blackPen; 

int main(int argc, char *argv[]) 
{ 
    blackBrush = new SolidBrush(Color(0, 0, 0)); 
    blackPen = new Pen(blackBrush); 
    return 0; 
}