首页 > 解决方案 > 祖父母,父母,孩子 - 参考问题

问题描述

我有一个孩子,父母和祖父母类的设置。一个祖父母有几个父母,存储在一个向量中,每个父母有几个孩子,也存储在一个向量中。每个对象都拥有对其所有者的引用。

在 MAIN 中,我将祖父母和父母的 ID 变量分别设置为 1,但是当我访问孩子父母的 ID 时,它为空。但是,当我访问孩子的父母祖父母时,正如预期的那样是 1。

为什么孩子的父母id不是1?

#ifndef HEADERH_H
#define HEADER_H

#include <vector>

class CHILD;
class PARENT;
class GRANDPARENT;

class CHILD{
public:
    int id;
    const PARENT &parent;
    CHILD(PARENT &parent):parent(parent){};};
class PARENT{
public:
    int id;
    const GRANDPARENT &grandparent;
    std::vector<CHILD> children;

    PARENT(GRANDPARENT &grandparent):grandparent(grandparent){};};
class GRANDPARENT
{
public:
    int id;
    std::vector<PARENT> parents;
    GRANDPARENT(){};
};

#endif

源文件

#include "Headerh.h"
#include <iostream>

int main(){

GRANDPARENT grandparent;

for(int i=0; i<=5; i++){
    PARENT parent(grandparent);

    for(int i=0; i<=5; i++){
        CHILD child(parent);
        parent.children.push_back(child);
    }
    grandparent.parents.push_back(parent);
}

grandparent.id = 1;
grandparent.parents[1].id = 1;

int test(grandparent.parents[1].children[1].parent.id);
int test0(grandparent.parents[1].children[1].parent.grandparent.id);

std::cout<<test<<" "<< test0<<std::endl;


return 0;
};

标签: c++classobjectreference

解决方案


推荐阅读