类中的c++对象引用
C++ object referencing in classes
我想知道如何在另一个对象内部存储对象的引用,并将该引用设置为私有属性。示例(伪代码):
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;
};
相关文章:
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 我们可以有一个 setter 成员函数作为从 const 对象引用的 const 吗?
- C++对象引用返回不同的值
- 对象引用中的字段以不同的方法返回不同的值
- 通过向构造函数其他对象引用页面来创建对象
- 为什么在对象引用恒定时允许更改为另一个类的指针的成员变量
- 如何在C++中读取 HDF5 对象引用
- C++ 未定义的对象引用
- 从函数返回 libconfig 类设置对象引用
- qt vsaddin错误对象引用未设置为对象的istanse
- 在这种情况下,为什么使用 *此必需的对象引用返回对象引用
- 基本C - 构造contaning对象引用,并将其作为方法参数传递
- C :将对象引用作为参数给出错误:呼叫class :: function()的匹配函数
- C++OOP基础知识-是否正确返回对象引用
- 使用对象引用(可能)在调用destructor后使用对象引用
- 创建返回对象引用的成员函数的最简单方法
- 如何在C++上使用对象引用删除对象
- JNI/Android NDK-维护全局对象引用
- 为什么有些类方法返回"*this"(self的对象引用)?
- 在C++中返回伪对象引用的规则