【问题标题】:declaring TBitmap globally全局声明 TBitmap
【发布时间】:2019-04-15 00:20:33
【问题描述】:

我想全局声明一个 TBitmap。

我尝试如下:

在一个方法中,这工作正常

std::auto_ptr<Graphics::TBitmap> RenderGraphic(new Graphics::TBitmap());

Graphics::TBitmap * RenderGraphic = new Graphics::TBitmap;

所以为了全局声明它,我在头文件中尝试了这个

Graphics::TBitmap *RenderGraphic;

还有这个在构造函数中

__fastcall TShipGraphic::TShipGraphic(TComponent* Owner)
: TForm(Owner)

{

  Graphics::TBitmap * RenderGraphic = new Graphics::TBitmap;

}

编译正常,但运行时,在第一次出现时抛出访问冲突异常

      RenderGraphic->Canvas->Pen->Color = clBlack;

请提前告知。

我使用的参考来源是C++ Builder Graphics Introduction

建议在构造函数中声明

【问题讨论】:

  • 在构造函数中声明和初始化一个局部变量而不是全局变量RenderGraphic
  • 全局到什么?您有多个表格?在顶部的主窗体 cpp somwhere 中使用 Graphics::TBitmap * RenderGraphic = new Graphics::TBitmap; 通常可以工作,但是...如果您从不同的窗体访问它,它可能会重复,除非您使用 static。更安全的是让它成为成员并在需要时共享它的指针。访问冲突通常是在您访问尚未初始化的事物时开始的。我们需要更多地了解您的应用架构...希望您没有使用线程...
  • @Spektra 在这种情况下,在一个表单中的所有方法中都是全局的。
  • 我放置了 Graphics::TBitmap * RenderGraphic = new Graphics::TBitmap;在 .cpp 顶部附近,在构造函数或任何其他方法之外,现在不会出现访问冲突错误,但是我的所有 RenderGraphic->Canvas-> 语句,如 MoveTo、LineTo、Polygon 似乎什么都不做当使用 Canvas->Draw(10, 10, RenderGraphic); 时,没有位图被绘制到画布上;保存到 .bmp 文件时,文件大小为零。也许这是一个不同的问题。
  • 好的,我已经工作了位图大小可能为零,因此没有出现任何内容。我确定这是为了绘制从文件加载的现有位图。 Rendergraphic->SetSize 解决了这个问题。但是为了在表单画布上透明地绘制,我仍然需要首先加载一个位图,尽管是一个纯白色的。 RenderGraphic->Transparent = true,除非已从文件加载位图,否则无效。这里有什么建议吗?

标签: c++builder rad-studio


【解决方案1】:

你需要实现一个单例。考虑只读情况(位图创建一次,没有setter函数)。

在 MyGraphics.h 中定义访问函数

#include <vcl.h>
TBitmap* GetRenderGraphic();

MyGraphics.cpp 中的实现

static std::unique_ptr<TBitmap> renderGraphic(new TBitmap());

TBitmap* GetRenderGraphic()
{
    return renderGraphic.get();
}

使用它(需要包括 MyGraphics.h)

GetRenderGraphic()->Canvas->Pen->Color = clBlack;

【讨论】:

  • 非常感谢@serge。我按照建议做了,但是我收到链接器错误 [ilink32 Error] Error: Unresolved external 'TShipGraphic::GetRenderGraphic()' referenced from E:\!STAB PROGRAM\BARRACUDA 2018E - SG CODE\BARRACUDA 2018E2\WIN32\DEBUG\OSSSHIPGRAPHIC .OBJ [ilink32 错误] 错误:无法执行链接
  • TShipGraphic::GetRenderGraphic() 好像没有实现或者项目中没有包含实现。当您使用类方法访问静态成员时,它也应标记为static
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-30
相关资源
最近更新 更多