且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

类中的C ++对象引用

更新时间:2023-01-17 20:37:13

与定义和使用 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);