c++ access variable from different switch case

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.


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.


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.

链接地址: http://www.djcxy.com/p/84428.html

上一篇: 如何初始化点数组?

下一篇: 来自不同开关柜的c ++访问变量