C++ object referencing in classes

2019-05-28 00:54发布

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?

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-05-28 01:28

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.

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);
查看更多
【Aperson】
3楼-- · 2019-05-28 01:35

You cannot reseat a reference, so you have to set it in the initializer list.

struct Foo {};

struct Bar {
  Bar(Foo &foo_) : foo(foo_) {}
  void set(Foo &foo_) { foo = foo_; } // copies, doesn't reseat
  Foo &foo;
};
查看更多
疯言疯语
4楼-- · 2019-05-28 01:44
bar::bar( foo & reference )
{
    fooreference = reference;
}

fooreference is just another object. By assigning, you are making a copy of the reference. Note that fooreference isn't an alias to the reference.

查看更多
登录 后发表回答