C++类中的对象引用
我想知道如何将一个对象的引用存储在另一个对象内部,并将该引用设置为私有属性。示例(伪代码):
class foo
{
public:
int size;
foo( int );
};
foo::foo( int s ) : size( s ) {}
class bar
{
public:
bar( foo& );
private:
foo fooreference;
};
bar::bar( foo & reference )
{
fooreference = reference;
}
foo firstclass( 1 );
bar secondclass( firstclass );
正如您所看到的,我只想能够将 foo 的引用存储在这个 bar 类中。我知道如何简单地将它带入一个方法并仅在该方法的范围内使用它,但在这里我想将它设置为私有属性。我该怎么做呢?
I am wondering how to store a reference of an object inside of another object, and also set that reference as a private property. Example (pseudo-code):
class foo
{
public:
int size;
foo( int );
};
foo::foo( int s ) : size( s ) {}
class bar
{
public:
bar( foo& );
private:
foo fooreference;
};
bar::bar( foo & reference )
{
fooreference = reference;
}
foo firstclass( 1 );
bar secondclass( firstclass );
As you may be able to see, I just want to be able to store the reference of foo inside this bar class. I know how to simply bring it into a method and use it just in the scope of that method, but here I want to set it as a private property. How would I go about doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
与定义和使用任何类成员的方式相同。
确保使用_member-initialiser初始化引用成员,而不是事后在构造函数主体中分配给它;请记住,引用必须被初始化并且以后不能被反弹。
The same way you define and use any class member.
Make sure you initialise the reference member with the _member-initialiser, instead of just assigning to it after-the-fact in the constructor body; recall that references must be initialised and cannot later be rebound.
fooreference
只是另一个对象。通过分配,您正在制作参考的副本。请注意,fooreference
不是reference
的别名。fooreference
is just another object. By assigning, you are making a copy of the reference. Note thatfooreference
isn't an alias to thereference
.您无法重新设置引用,因此必须在初始值设定项列表中设置它。
You cannot reseat a reference, so you have to set it in the initializer list.