[英]Refer from 1 cpp file to another C++
从1个文件引用到另一个文件时遇到一些问题。
我有2个VCL表格:
-OpenPlotFile-SelectElement
在我的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
。
我该如何解决? 或者如何在不为NULL
情况下将plotFile
传递到另一个文件?
仅供参考:全局变量很丑陋,应尽可能避免使用。 封装和抽象是您的朋友。 但是要回答你的问题:
如果plotFile
通过AnsiString plotFile;
声明,则属于您的头文件AnsiString plotFile;
每个翻译单元都有自己的副本。 您需要在一个* .cpp文件中定义变量,并在标头中将其声明为extern。
从C ++标准:
3.5程序与链接
当一个名称具有外部链接时,它表示的实体可以由其他翻译单位范围或同一翻译单位其他范围内的名称引用。
因此,必须在头文件中放置以下内容:
extern AnsiString plotFile;
在一个cpp文件中定义变量:
AnsiString plotFile;
不要为此使用全局变量,如果您总是使用它,迟早会遇到麻烦。 它引起的一个问题是您只能使用一次表单实例,因为它占用了全局变量。
我想在所有平台/系统/等等上都有一个通用的解决方案。您必须以某种方式将变量传递给要显示的form / dialog / etc 类实例 。
您似乎正在使用Borland Builder C ++或Embarcadero。 解决问题的正确方法是将AnsiString plotFile
添加为SelectElement形式的成员变量,并使用访问器方法进行设置。 可以在此处找到示例代码:
http://bcbjournal.org/articles/vol2/9810/Sharing_data_and_methods_between_forms.htm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.