Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;-如何将变量从一种形式传递到另一种形式?_C++_Windows_Forms - Fatal编程技术网

C++ C++;-如何将变量从一种形式传递到另一种形式?

C++ C++;-如何将变量从一种形式传递到另一种形式?,c++,windows,forms,C++,Windows,Forms,我有一个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 her

我有一个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;

不太清楚你的要求是什么,但我假设你想从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
}

由于预处理器指令导致双重包含,因此出现错误。 要避免这种情况,可以使用pragma保护

表格1.h:

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

#include "Form1.h"

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

首先,您可以使用解决多重包含问题

然后,您可以在标头中使用extern关键字声明一个全局变量,并在实现文件中插入该值

例如:

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

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

现在,您可以
#在其他文件中的任意位置随时包含“mylib.h”
,并访问相同的变量

为了帮助您,我们需要查看您遇到问题的代码。在Form2.h中包含Form1.h并直接访问?Form2是一个变量,您可以通过在Form1.h中包含Form2.h来访问变量Form2。它是双向的;)@实际上是外星人。它只是给了我一个错误,因为我猜你不能有两个文件,包括彼此。让我猜猜,“循环单位引用”?Idk这是什么,但当我包括Form1.h到Form2.h时它不起作用:\n不。我已经在Form1.h中包含了Form2.h,我需要将一个变量从Form1传递到Form2,而不在Form2.h中包含Form1.h。如果你想要一个叫做“静态”的函数,请在我编辑我的评论时5分钟后再查看。顺便说一句,Form1和Form2不是类。它们是Windows窗体应用程序中的窗体。他们也使用.NETFrask.OHK,你应该在这个问题中明确地指定(即使是标签,问题看起来像是普通的C++头文件问题)。不幸的是,在这方面我真的帮不了你。@你现在提到的.Net是一个自由职业者。。。它是Windows应用Visual C++还是Windows应用Visual C++?