简体   繁体   English

C ++初始化为函数

[英]C++ initialization as function

I am spitting through some old C++ code. 我在吐槽一些旧的C ++代码。 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 无法访问“ Gdiplus :: Pen :: Pen(const Gdiplus :: Pen&)”(在“ c:\\ Program Files(x86)\\ Windows Kits \\ 8.1 \\ Include \\ um \\ gdipluspen.h”的第452行声明)

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 更新,以回应OP的评论

Another option (provided Pen meets the requirements of being the value type of std::map ): 另一个选择(提供的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];
}

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: 我的解决方案是直接定义一个指针而不是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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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