我这样做了吗?我正在尝试委托一个C++类构造函数,因为它基本上是相同的代码重复3次..我读了C++ x11并读到g ++ 4.7.2允许这样但我不确定我是否正在这样做对:
Bitmap::Bitmap(HBITMAP Bmp)
{
//Construct some bitmap stuff..
}
Bitmap::Bitmap(WORD ResourceID)
{
HBITMAP BMP = (HBITMAP)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(ResourceID), IMAGE_BITMAP, 0, 0, LR_SHARED);
Bitmap(BMP); //Delegates to the above constructor? Or does this create a temporary?
}
Run Code Online (Sandbox Code Playgroud)
或者我需要这样做:
Bitmap::Bitmap(HBITMAP Bmp)
{
//Construct some bitmap stuff..
}
Bitmap::Bitmap(WORD ResourceID) : Bitmap((HBITMAP)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(ResourceID), IMAGE_BITMAP, 0, 0, LR_SHARED))
{
}
Run Code Online (Sandbox Code Playgroud)
Pub*_*bby 40
你需要做第二个.委托构造函数只能在构造函数的初始化列表中工作,否则你只会创建一个临时的或者像你提到的那样的其他错误.
log*_*og0 40
正确的语法是
struct Foo {
Foo(char x, int y) : _x{x}, _y(y) {}
Foo(int y) : Foo('a', y) {}
char _x;
int _y;
};
Run Code Online (Sandbox Code Playgroud)
您的第一个示例创建了一个立即销毁的临时文件.