类中的c++对象引用

C++ object referencing in classes

本文关键字:对象引用 c++      更新时间:2023-10-16

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

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类中。我知道如何把它带入一个方法并在那个方法的范围内使用它,但这里我想把它设为私有属性。我该怎么做呢?

与定义和使用任何类成员的方式相同。

确保用_member- initializer初始化引用成员,而不是事后在构造函数体中对其赋值;请记住,引用必须初始化,以后不能反弹。

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只是另一个对象。通过赋值,您正在创建引用的副本。注意,fooreference不是reference的别名。

你不能重置引用,所以你必须在初始化列表中设置它。

struct Foo {};
struct Bar {
  Bar(Foo &foo_) : foo(foo_) {}
  void set(Foo &foo_) { foo = foo_; } // copies, doesn't reseat
  Foo &foo;
};