类中的C ++对象引用

问题描述:

我想知道如何在另一个对象内部存储对象的引用,并将该引用设置为私有属性.示例(伪代码):

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 );

您可能会看到,我只想能够在此bar类中存储foo的引用.我知道如何简单地将其带入方法并仅在该方法的范围内使用它,但是在这里,我想将其设置为私有属性.我将如何去做?

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?

与定义和使用 any 类成员的方式相同.

The same way you define and use any class member.

确保使用_member-initialiser 初始化参考成员,而不是在构造函数主体中事后分配给它.记得引用必须被初始化,以后不能反弹.

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.

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);