Change label text from different header file, Visual C++ 2010?

荒凉一梦 提交于 2019-12-11 07:41:41

问题


I am using Visual C++ 2010 Express. I have a form (Form1.h) that contains a button (btn1) and a label (label1).

When I click the button, I would like to call a function from a different header file (testing.h) that will then proceed to change the text in the label.

What I have is something like this...

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();
    }
};

Where testing.h is something like...

#ifndef _TESTING_FUNCS
#define _TESTING_FUNCS

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

#endif

When I try to compile and run it, I get errors saying that 'label1' is an undeclared identifier (within testing.h), and an error referring to the "left of '->Text' must point to class/struct/..."

I am new to C++ and usually use Java, so there are a few new things for me here. To me, there are two obvious options:

1) Pass the label to the function as an argument

2) Somehow access the label from the testing.h header file, sans reference

But I'm not really sure how to do either.


回答1:


The label is a private variable of a class and just like in Java is not accessible from the outside, especially not in static context. You can pass the label, or you can create an accessor function in your Form and pass the whole form.

Example for passing the label:

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

Calling it:

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


来源:https://stackoverflow.com/questions/20980056/change-label-text-from-different-header-file-visual-c-2010

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!