I defined a class that I want to use for building a window. One of the fields is hWnd and when the member function create() is called the 开发者_开发问答HWND to the created window is stored there. I overloaded the (HWND) cast to return that value:
operator HWND() { return(hWnd); }
My program started crashing when I attempted to create child windows to the first, main window I created and I tracked it down to an odd value being returned by the typecast. I defined a typical getter function, getHwnd(), that works fine but the typecast just returns trash. Is there something that I'm missing?
The class definition:
class WindowBuilder
{
public:
WindowBuilder(FullWindow &fullWindow);
operator HWND() { return(hWnd); }
void SetCaption(char const * caption) { windowName = caption; }
void SetMenu(int resourceId);
void SetRender(RECT rect, HWND parent);
void SetButton(HWND parent);
void Create();
void Show(int nCmdShow = SW_SHOWNORMAL);
HWND getHwnd () { return(hWnd); }
protected:
FullWindow & window;
HWND hWnd;
char const * windowName;
DWORD style;
int x;
int y;
int width;
int height;
HWND hWndParent;
HMENU hMenu;
void * data;
};
Example of calling:
FullWindow renderWindowClass("STATIC", GlobalInstance, WndProc);
renderWindow = new WindowBuilder(renderWindowClass);
renderWindow->SetRender(rect,mainWindow->getHwnd()); // used to be (HWND)mainWindow
renderWindow->Create();
renderWindow->Show(CmdShow);
/*RenderWindow = ::CreateWindow("STATIC", NULL, WS_CHILD | WS_VISIBLE | WS_BORDER,
DEFAULT_BUTTON_WIDTH, 0, rect.right-rect.left-DEFAULT_BUTTON_WIDTH,
rect.bottom - rect.top, Window, NULL, hInstance, NULL);*/
You don't show the definition of mainWindow
, but based on your use of ->, I would assume that it is a pointer to a WindowBuilder. So when you do (HWND)mainWindow
, you are casting the pointer value to an HWND rather than invoking your cast operator. To invoke your cast operator, you would need to do something like (HWND)(*mainWindow)
.
Having said that, I feel obliged to say that you would have a cleaner design if you do not use cast overloads in this way. They can lead to subtle bugs due to automatic casts that can be hard to spot in the code. Using an explicit getHwnd()
member is much more clear and reliable.
精彩评论