【问题标题】:C++ - How do you pass a variable from one form to another?C++ - 如何将变量从一种形式传递到另一种形式?
【发布时间】:2013-03-30 02:36:55
【问题描述】:

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

编辑:

我就是这样解决的

这就是我修复它的方法。

Form1.h

#include "Form1.h"

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

Form2.h

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

【问题讨论】:

  • 为了帮助您,我们需要查看您遇到问题的代码。
  • Form2.h中包含Form1.h直接访问? Form2 是一个变量,您可以通过在 Form1.h 中包含 Form2.h 来访问变量 Form2。它适用于两种方式;)
  • @The_aLiEn 实际上。它只是给了我一个错误,因为我猜你不能有 2 个文件,包括彼此。
  • 让我猜猜,“圆形单位参考”?
  • Idk 那是什么但是当我将 Form1.h 包含到 Form2.h 时它不起作用:\

标签: c++ windows forms


【解决方案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
}

【讨论】:

  • 不。我已经在 Form1.h 中包含了 Form2.h,我需要将一个变量从 Form1 传递给 Form2,而不在 Form2.h 中包含 Form1.h
  • 啊,我明白了。你想要一个叫做“静态”的函数,然后在我编辑我的评论时在 5 分钟内查看
  • 顺便说一句,Form1 和 Form2 不是类。它们是 Windows 窗体应用程序中的窗体。他们还使用 .NET Framework。
  • ohh k,您应该在问题中简要说明这一点(即使使用标签,问题也有点像普通的 C++ 头文件问题)。不幸的是,那时真的无法为您提供帮助。
  • @FreelanceCoder 你现在提到.Net...它是Windows Application Visual C# 还是Windows Application Visual C++?
【解决方案2】:

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

Form1.h:

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

Form2.h:

#include "Form1.h"

【讨论】:

    【解决方案3】:

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

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

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

    例如:

    //file: mylib.h
    #ifndef MYLIB_H
    #define MYLIB_H
    extern int myGlobalVar;
    #endif
    
    //file: mylib.cpp
    #include "mylib.h"
    int myGlobalVar = 123;
    

    现在您可以在其他文件的任何位置#include "mylib.h" 任意多次访问同一个变量

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-22
      • 2015-06-06
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 2015-06-23
      相关资源
      最近更新 更多