-2

我有一个 Form1.h 和一个 Form2.h

Form1.h 已经包含 Form2.h,因为我通过单击 Form1 中的按钮来启动 Form2。那么我如何将变量从 Form1.h 传递到 Form2.h

这是 Form1.h 的示例

#include "Form2.h"

String^ str = "Hello World"; //This variable needs to be passed to Form2.h

//Other windows forms application code here

Form2.h 的一个例子

//#include "Form1.h" this will cause an error

//How would i pass variable str to here?

//Other windows forms application code here

编辑:

这就是我修复它的方法

这就是我修复它的方式。

表格1.h

#include "Form1.h"

Form2^ frm = gcnew Form2;
frm->Username = "text here";//This passes the variables.
frm->Password = "other text";

表格2.h

public: String^ Username;
public: String^ Password;
4

3 回答 3

1

不完全确定您的要求,但我假设您想从Form1类中设置Form2类中的变量?如果是这样的话:

class Form1{
  private:
    int data;
  public:
    Form1(){data=4;}
    int getData(){return data;}  //returns Form1 data variable
    void setForm2Data(Form2&);   //sets Form2 data
};

class Form2{
  private:
    int data;
  public:
    void setData(int inData){data = inData;}
};

void Form1::setForm2Data(Form2 &o){
  o->setData(getData());  //argument is a Form2 object, "setData" can set that objects data variable
}
于 2013-03-30T02:55:11.850 回答
0

您会收到一个错误,因为您的预处理器指令会导致双重包含。为避免这种情况,您可以使用编译指示守卫

表格1.h:

#ifndef FORM1_H
   #define FORM1_H
   #include "Form2.h"
   extern string str = "Hello World";
#endif

表格2.h:

#include "Form1.h"
于 2013-03-30T03:22:07.713 回答
0

有几种方法..一种是使用全局变量(不一定是最好的方法..取决于具体情况)

First, you can solve the multiple inclusion problem by using include guard.

Then you can declare a global variable using extern keyword in the header, and plug in the value in the implementation file.

For example:

//file: mylib.h
#ifndef MYLIB_H
#define MYLIB_H
extern int myGlobalVar;
#endif

//file: mylib.cpp
#include "mylib.h"
int myGlobalVar = 123;

Now you can #include "mylib.h" anywhere in other file as many time as you like and access the same variable

于 2013-03-30T03:49:13.207 回答