简体   繁体   中英

C++ initialization as function

I am spitting through some old C++ code. In it, I declare a local variable like this:

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

This seems to call the constructor.

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. Of course, I can define a global variable

Pen blackPen;

But now I don't know how to initialize it:

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

seems the most reasonable, but I get an error:

"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

The following snippet shows this behavior:

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

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.

One option is to provide access to the variable through a function.

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

Then, you will have access to object anywhere the function declaration is available. It will be initialized when the function is called the first time.

Update, in response to OP's comment

Another option (provided Pen meets the requirements of being the value type of 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];
}

Now, you can use:

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

My solution was to define a pointer instead of a Pen directly, and then use the constructor that works from a brush:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM