2014-01-07 78 views
1

我正在使用Visual C++ 2010 Express。我有一個包含按鈕(btn1)和標籤(label1)的表單(Form1.h)。從不同的頭文件Visual C++ 2010中更改標籤文本?

當我點擊按鈕時,我想從不同的頭文件(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頭文件訪問標籤,SANS參考

但我不知道該怎麼做。

回答

2

該標籤是一個類的私有變量,就像在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); 
} 
+0

完美,謝謝! – Birrel