【问题标题】:Change label text from different header file, Visual C++ 2010?从不同的头文件更改标签文本,Visual C++ 2010?
【发布时间】:2014-01-25 15:11:33
【问题描述】:

我正在使用 Visual C++ 2010 Express。我有一个表单 (Form1.h),其中包含一个按钮 (btn1) 和一个标签 (label1)。

当我单击按钮时,我想从不同的头文件 (testing.h) 调用一个函数,然后继续更改标签中的文本。

我有的是这样的......

Form1.h

#include "testing.h"

... standard form code generated by Visual Studio

private: System::Windows::Forms::Label^  label1;

...

private: System::Void btn1_Click(System::Object^  sender, System::EventArgs^  e) {
        testfunc1();
    }
};

testing.h 类似于...

#ifndef _TESTING_FUNCS
#define _TESTING_FUNCS

void testfunc1(){
    label1->Text = "Text has been changed from outside.";
}

#endif

当我尝试编译和运行它时,我收到错误提示 'label1' is an undeclared identifier(在 testing.h 中),以及一个错误指的是“left of '->Text' must point to class/struct/...

我是 C++ 新手,通常使用 Java,所以这里对我来说有一些新东西。对我来说,有两个明显的选择:

1) 将标签作为参数传递给函数

2) 以某种方式从testing.h 头文件中访问标签,无参考

但我也不确定该怎么做。

【问题讨论】:

    标签: winforms visual-studio-2010 c++-cli header-files


    【解决方案1】:

    标签是类的私有变量,就像在 Java 中一样,不能从外部访问,尤其是在静态上下文中。您可以传递标签,也可以在您的表单中创建一个访问器函数并传递整个表单。

    传递标签的例子:

    void testfunc1(System::Windows::Forms::Label^ someLabel)
    {
        someLabel->Text = "Text has been changed from outside.";
    }
    

    调用它:

    System::Void btn1_Click(System::Object^  sender, System::EventArgs^  e) 
    {
        testfunc1(label1);
    }
    

    【讨论】:

      猜你喜欢
      • 2014-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多