gpt4 book ai didi

c++ - 从 1 个 cpp 文件引用到另一个 C++

转载 作者:行者123 更新时间:2023-11-28 00:12:30 24 4
gpt4 key购买 nike

我在从一个文件引用到另一个文件时遇到了一些问题。

我有 2 个 VCL 表单:
- 打开绘图文件- 选择元素

在我的 Plotfile 中我有一个 openDialog:

void __fastcall TPlotFileForm::btn_fileselectClick(TObject *Sender)
{

AnsiString message;

//Dialog opties instellen

OpenDialog->Options << ofFileMustExist;
OpenDialog->Filter ="PPD files (*.PPD) |*.ppd |PLOT files (PLOT.*) | plot.*";
OpenDialog->FilterIndex = 2;

if (OpenDialog->Execute())
{
plotFile = OpenDialog->FileName;
Itxt_plotfile->Text=plotFile;

try
{
TFileStream *plotStream = new TFileStream(plotFile, fmOpenRead);
TStringStream *plotString = new TStringStream();

plotString->CopyFrom(plotStream, plotStream->Size);
FileBuffer = plotString->DataString;
delete plotStream;
delete plotString;

message = "Make your choice what to plot";
ListBox1->Items->Add(message);
message = "Default is everything, on insulation and with automatic weepholes at 1000 mm...";
ListBox1->Items->Add(message);
message = "Accept with the OK button...";
ListBox1->Items->Add(message);

btn_OK->Enabled=true;//Knop activeren nadat file is gekozen
}
catch(EStreamError &e)
{
ShowMessage(e.Message);
}
}

在这个文件中我有一个plotFile,这是文件目录。我想将该值转换为另一种形式:SelectElement

我现在的做法很简单:我将 AnsiString plotFile; 添加到 OpenPlotFile.h

我在 SelectElement 文件中包含 OpenPlotFile.h。

#include "PlotFileScreen.h"
void __fastcall TSelectElementForm::FormShow(TObject *Sender)
{
element *ElementArray = new element[100];
ElementArray = GetElementInfo();
Itxt_plot_file->Text = plotFile;
Itxt_ordernumber->Text = ElementArray[0].ON;
Itxt_element_id->Text = ElementArray[0].MO;
Itxt_type->Text = ElementArray[0].SN;
Itxt_concrete->Text = ElementArray[0].el_concrete_height;
Itxt_Insulation->Text = ElementArray[0].el_iso_height;
Itxt_Length->Text = ElementArray[0].el_length;
Itxt_Width->Text = ElementArray[0].el_width;
Itxt_Weight->Text = ElementArray[0].el_weight;
Itxt_slabmark->Text = "";
Itxt_reinforce->Text = ElementArray[0].OW;
}

我的程序可以编译并且运行良好,但奇怪的是,当我调试时,在两个文件中它都显示:plotFile = NULL

我该如何解决这个问题?或者如何将 plotFile 传递给另一个文件而不是 NULL

最佳答案

仅供引用:全局变量很难看,应尽可能避免使用。封装和抽象是你的 friend 。但要回答你的问题:

如果 plotFile 属于您的头文件,通过 AnsiString plotFile; 声明它,每个翻译单元都有自己的拷贝。您需要在一个 *.cpp 文件中定义变量,并在 header 中将其声明为 extern。

来自 C++ 标准:

3.5 Program and linkage

When a name has external linkage , the entity it denotes can be referred to by names from scopes of other translation units or from other scopes of the same translation unit.

所以在你的头文件中你必须放置这个:

extern AnsiString plotFile;

在一个 cpp 文件中定义变量:

AnsiString plotFile;

关于c++ - 从 1 个 cpp 文件引用到另一个 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32269779/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com