How to implement a global variable if C++/CLI doesn't support it at all?
-
I'm trying to build a really simple class with member variables and member functions for learning. I am trying to achieve the following code inside btn_User1_Click, however since user1 is not globally declared, it couldn't find the variable. At the same time, if I tried to declare this myUser^ user1 = gcnew user1 (1002); outside the function , it gives an error syntax error missing ';' before '^'
myUser.h
#pragma once
ref class myUser
{public:
myUser(unsigned int user_id) :id(user_id) {...
}
private:
unsigned int id{ 0 };public:
System::Void increment\_UserID() {
id = id + 1;
}
};
MyForm.cpp
namespace FACEDControllerGUI {
System::Void MyForm::MyForm\_Load(System::Object^ sender, System::EventArgs^ e) { myUser^ user1 = gcnew user1 (1002); myUser^ user2 = gcnew user1 (1005); } System::Void MyForm::btn\_User1\_Click(System::Object^ sender, System::EventArgs^ e) { user1->increment\_UserID(); } System::Void MyForm::btn\_User2\_Click(System::Object^ sender, System::EventArgs^ e) { user2->increment\_UserID(); }
} // end namespace
-
I'm trying to build a really simple class with member variables and member functions for learning. I am trying to achieve the following code inside btn_User1_Click, however since user1 is not globally declared, it couldn't find the variable. At the same time, if I tried to declare this myUser^ user1 = gcnew user1 (1002); outside the function , it gives an error syntax error missing ';' before '^'
myUser.h
#pragma once
ref class myUser
{public:
myUser(unsigned int user_id) :id(user_id) {...
}
private:
unsigned int id{ 0 };public:
System::Void increment\_UserID() {
id = id + 1;
}
};
MyForm.cpp
namespace FACEDControllerGUI {
System::Void MyForm::MyForm\_Load(System::Object^ sender, System::EventArgs^ e) { myUser^ user1 = gcnew user1 (1002); myUser^ user2 = gcnew user1 (1005); } System::Void MyForm::btn\_User1\_Click(System::Object^ sender, System::EventArgs^ e) { user1->increment\_UserID(); } System::Void MyForm::btn\_User2\_Click(System::Object^ sender, System::EventArgs^ e) { user2->increment\_UserID(); }
} // end namespace
-
You are creating
user1
anduser2
inside theMyForm_Load
method, so as soon as that method ends the two variables disappear. You should create them in the class definition ofMyForm
so they are available to all methods of the class.I have mentioned this following: At the same time, if I tried to declare this myUser^ user1 = gcnew user1 (1002); outside the function , it gives an error syntax error missing ';' before '^' Fortunately, I have solved my problem. It is due to #include function of the class is placed in the .cpp file, instead of the .h file