C++在类构造函数中使用引用
我知道你绝对可以在类中拥有一个引用变量,但是有没有比拥有一个占位符对象更“优雅”的方法来做到这一点?这是我当前的代码(我不喜欢这是如何完成的):
Object placeholder = Object();
class MyClass {
private:
Object& variable = placeholder;
}
编辑: 引用变量显然无法在运行时重新分配,因此我的示例甚至不起作用。但是,我仍然想知道如何在我的类中包含引用变量。
I know you can definitely have a reference variable in a class, but is there any more "elegant" way to do this than to have a placeholder object? This is my current code (I don't like how this is being done):
Object placeholder = Object();
class MyClass {
private:
Object& variable = placeholder;
}
EDIT:
Reference variables apparently cannot be reassigned during runtime so my example doesn't even work. I would, however, still like to know how to include reference variables in my classes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我希望此链接有帮助: 引用变量有错误,必须在构造函数基/成员初始值设定项中初始化
它不会直接告诉您是否有一种优雅的方法,但它更多地扩展了可能导致错误的方法,因此,您可能需要考虑去使用此链接中提到的基本方法!
I hope this link helps: Reference variable with error, must be initialized in constructor base/member initializer
It doesn't directly tell you if there is an elegant way but it expands more on the approaches that might lead to an error, therefore, you might want to consider going with the basic approach mentioned in this link!