c++ access variable from different switch case

筅森魡賤 提交于 2021-02-11 00:35:31

问题


I'm creating a win32 application and initialized my statusbar width variables in my WM_CREATE switch case.

case WM_CREATE:
  {
    int statwidths[] = { 200, -1 };
  }
  break;

I would like to access statwidths[ 0 ] in my WM_SIZE switch case as that number will be used to determine the size of the rest of my windows in my program.

case WM_SIZE:
  {
    int OpenDocumentWidth = statwidths[ 0 ];
  }
  break;

Is there a way to do this? They are both in the same switch statement in the same file.


回答1:


If these are both in the same switch statement then, absolutely not. Consider

switch (n) {
    case 1: {
    }
    case 2: {
    }
}

What happens in the case 1 scope only happens when n is 1. If we declare a variable there and then we call this code with n=2, the variable is not declared.

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.
    }
}

You can declare the variable outside the switch but you should not then assume the previous case has done its thing unless the switch is inside a loop.

Dang, last time I try to do this on a kindle.




回答2:


You will need to make a class for your window handling it should look like this:

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

It is just a small piece of code you need, but you can use it as a base for you, hope that helps.



来源:https://stackoverflow.com/questions/19263831/c-access-variable-from-different-switch-case

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