[英]c++ access variable from different switch case
我正在創建一個Win32應用程序,並在WM_CREATE開關中初始化了狀態欄寬度變量。
case WM_CREATE:
{
int statwidths[] = { 200, -1 };
}
break;
我想在WM_SIZE開關的情況下訪問statwidths [0],因為該數字將用於確定程序中其余窗口的大小。
case WM_SIZE:
{
int OpenDocumentWidth = statwidths[ 0 ];
}
break;
有沒有辦法做到這一點? 它們都在同一文件的同一switch語句中。
如果它們都在同一個switch語句中,那么絕對不是。 考慮
switch (n) {
case 1: {
}
case 2: {
}
}
在情況1的作用域中,只有在n為1時才會發生什么。如果我們在那里聲明一個變量,然后以n = 2調用此代碼,則不會聲明該變量。
int n;
if(fileExists("foo.txt"))
n = 2;
else
n = 1;
switch (n) {
case 1: {
ostream outfile("foo.txt");
...
break;
}
case 2: {
// if outfile were to be initialized as above here
// it would be bad.
}
}
您可以在開關外部聲明變量,但是除非開關位於循環內,否則您不應該假定先前的情況已經完成。
堂,上次我嘗試着點燃它。
您將需要為窗口處理創建一個類,該類應如下所示:
class Foo
{
private:
int* statwidths;
HWND hwnd;
public:
Foo(){};
~Foo(){};
bool CreateWindow()
{
//some stuff
hwnd = CreateWindowEx(...);
SetWindowLongPtr(hwnd GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
//some stuff
}
static LRESULT callback(HWND hwnd, ...)
{
Foo* classInfo = reinterpret_cast<Foo *>(GetWindowLongPtr(window, GWLP_USERDATA));
case WM_CREATE:
{
classInfo->statwidths = new int[2];
classInfo->statwidths[0] = 200;
classInfo->statwidths[1] = -1;
break;
}
case WM_SIZE:
{
int OpenDocumentWidth = classInfo->statwidths[0];
}
case WM_CLOSE:
{
delete [] classInfo->statwidths;
}
}
};
它只是您需要的一小段代碼,但您可以將其用作基礎,希望能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.