我有这个代码,但它不是一个实际的例子.
防爆.
class Animal
{
int i;
int& ref;
public:
Animal() : ref(i)
{
}
};
Run Code Online (Sandbox Code Playgroud)
任何人都可以提供一个真实的例子,其中ref需要作为一个类成员,以便我能更好地理解它吗?
任何时候,某个类 A 的多个对象都需要引用同一类或某个其他类的单个共享实例;例如,几个People可以都有相同的母亲和/或父亲:
class Person {
private:
Person &mother_;
Person &father_;
public:
Person(Person &mother, Person &father) : mother_(mother), father_(father) {}
// ...
}
Run Code Online (Sandbox Code Playgroud)