委托构造函数 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13961037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delegate Constructor C++
提问by Brandon
Am I doing this right? I'm trying to delegate a C++ class constructor as it's basically the same code repeating 3 times.. I read up on C++x11 and read that g++ 4.7.2 allows this but I'm not sure if I'm doing it right:
我这样做对吗?我正在尝试委托一个 C++ 类构造函数,因为它基本上是重复 3 次的相同代码。对:
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?
}
OR do I need to do:
或者我需要做什么:
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))
{
}
采纳答案by Pubby
You need to do the second. Delegating constructors only works in the constructor's initialization list, otherwise you'll just create a temporary or do other mistakes like you mentioned.
你需要做第二个。委托构造函数只在构造函数的初始化列表中起作用,否则你只会创建一个临时的或像你提到的那样做其他错误。
回答by log0
The correct syntax is
正确的语法是
struct Foo {
Foo(char x, int y) : _x{x}, _y(y) {}
Foo(int y) : Foo('a', y) {}
char _x;
int _y;
};
Your first example creates a temporary that is destroyed right away.
您的第一个示例创建了一个立即销毁的临时文件。
回答by rahul
The second example using the initializer list is the correct one . First example is going to end up creating a temporary object.
第二个使用初始化列表的例子是正确的。第一个示例将最终创建一个临时对象。