C++ '' 的构造函数必须显式初始化引用成员 ''
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19576458/
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
Constructor for '' must explicitly initialize the reference member ''
提问by clankill3r
I have this class
我有这堂课
class CamFeed {
public:
// constructor
CamFeed(ofVideoGrabber &cam);
ofVideoGrabber &cam;
};
And this constructor:
而这个构造函数:
CamFeed::CamFeed(ofVideoGrabber &cam) {
this->cam = cam;
}
I get this error on the constructor: Constructor for '' must explicitly initialize the reference member ''
我在构造函数上收到此错误:''的构造 函数必须显式初始化引用成员 ''
What is a good way to get around this?
解决这个问题的好方法是什么?
回答by juanchopanza
You need to use the constructor initializer list:
您需要使用构造函数初始值设定项列表:
CamFeed::CamFeed(ofVideoGrabber& cam) : cam(cam) {}
This is because references must refer to something and therefore cannot be default constructed. Once you are in the constructor body, all your data members have been initialized. Your this->cam = cam;
line would really be an assignment, assigning the value referred to by cam
to whatever this->cam
refers to.
这是因为引用必须引用某些东西,因此不能默认构造。进入构造函数体后,所有数据成员都已初始化。您的this->cam = cam;
行实际上是一个分配,将引用的值分配给引用的cam
任何内容this->cam
。