简单的编程问题C ++ [英] Simple programming question C++
问题描述
我是编程新手,所以请原谅我,英语不是我的第一语言。我正在学习CLR格式的C ++,所以我有以下内容:
test.h
宣布全球变量int x;
I am totally new to programming so please forgive me and english is not my first language. I am learning C++ in CLR format so I have the following:
test.h
Declared global variable int x;
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
x = 5;
test ( x )
}
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e)
{
test(x) -> Still cannot access the variable x from button1.. :(
}
更新:在cpp中创建另一个函数,在test.h中调用它。 />
Update: Created another function in cpp, called it over here in test.h
Function int test ( int i)
{
int i;
return i;
}
推荐答案
确切地理解你想要的东西有点难,但我觉得它有点像这个;
It's a little bit difficult understanding exactly what you want, but I think it's something like this;
- 按下按钮1时,将某个值存储在某个变量中。
- 当按钮2为按下,以某种方式使用按下按钮1存储的值。
如果是这样的话可能有助于你开始;
If that's the case something like this might help you get started;
#include "stdafx.h"
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
ref class MyForm : public Form {
private:
Button^ button1;
Button^ button2;
Label^ label;
int result;
public:
MyForm();
void OnClick1(System::Object ^sender, System::EventArgs ^e);
void OnClick2(System::Object ^sender, System::EventArgs ^e);
};
// Constructor initializing the buttons and label, and adding them to the form
MyForm::MyForm() {
Text = "My Form";
button1 = gcnew Button();
button1->Text = "Button 1 (add 1)";
button1->SetBounds(10, 10, 100, 32);
button1->Click += gcnew System::EventHandler(this, &MyForm::OnClick1);
button2 = gcnew Button();
button2->Text = "Button 2 (add 5)";
button2->SetBounds(10, 50, 100, 32);
button2->Click += gcnew System::EventHandler(this, &MyForm::OnClick2);
label = gcnew Label();
label->Text = "Result area";
label->SetBounds(10, 90, 200, 32);
Controls->Add(button1);
Controls->Add(button2);
Controls->Add(label);
}
// Click handler for button1, this will add 1 to the member variable result
void MyForm::OnClick1(System::Object ^sender, System::EventArgs ^e) {
result += 1;
label->Text = String::Format("Pressed 1, result is {0}", result);
}
// Click handler for button2, this will add 5 to the member variable result
void MyForm::OnClick2(System::Object ^sender, System::EventArgs ^e) {
result += 5;
label->Text = String::Format("Pressed 2, result is {0}", result);
}
int main(array<System::String ^> ^args) {
MyForm^ form = gcnew MyForm();
Application::Run(form);
return 0;
}
MyForm
类保存按钮的变量,还有一个结果
变量,该变量由类中的每个方法共享。因此,当按钮1或2修改该值时,另一个按钮的点击处理程序总是可以读取它。
希望这会有所帮助,
Fredrik
The MyForm
class holds variables for the buttons, but also a result
variable that is shared by every method in the class. Thus, when button 1 or 2 modifies the value, the click-handler for the other button can always read it.
Hope this helps,
Fredrik
这篇关于简单的编程问题C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!