C++ object referencing in classes

喜夏-厌秋 提交于 2019-12-06 16:01:07

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

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;
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!