用对象创建父/子关系

Creating a Parent/Child relationship with objects

本文关键字:关系 对象 创建      更新时间:2023-10-16

好的,我在创建父/子关系时遇到了一些麻烦。我能解释的最简单的方法是,有一个对象,有一个指向同一类型的另一个对象的引用(或指针),然后是一个指向更多对象的子引用(或指针)数组。该对象应该具有。getchildren、。addchild、。removechild、。getparent、。changparent等函数。我有一个可怕的时间与指针,如果有人可以帮助与代码,那将是伟大的。此外,如果有人好奇,我将使用这种方法与3D模型。基本模型(父模型)将是对象的中心,所有子模型都可以自由移动,并且当父模型移动时,它会引起子模型移动。

代码:

class Base {
  protected:
    Base* parent;
    std::vector<Base*> children;
    std::string id;
    POINT pos, rot;
  public:
    Base (void);
    Base (std::string);
    Base (POINT, POINT, std::string);
    Base (const Base&);
    ~Base (void);
    POINT getPos (void);
    POINT getRot (void);
    Base getParent (void);
    Base getChildren (void);
    void addChild (Base&);
    void removeChild (Base&);
    void changeParent (Base);
    void move (int, int);
    void rotate (int, int);
    void collide (Base);
    void render (void);
};
Base::Base (void) {
    this->id = getRandomId();
    this->pos.x = 0; this->pos.y = 0; this->pos.z = 0;
    this->rot.x = 0; this->rot.y = 0; this->rot.z = 0;
};
Base::Base (std::string str) {
    this->id = str;
    this->pos.x = 0; this->pos.y = 0; this->pos.z = 0;
    this->rot.x = 0; this->rot.y = 0; this->rot.z = 0;
};
Base::Base (POINT p, POINT r, std::string str) {
    this->id = str;
    this->pos = p;
    this->rot = r;
};
Base::Base (const Base& tocopy) {
    this->parent = tocopy.parent;
    this->children = tocopy.children;
    this->id = tocopy.id;
    this->pos = tocopy.pos;
    this->rot = tocopy.rot;
};
Base::~Base (void) {
};
void Base::changeParent (Base child) {
    *(this->parent) = child;
};
int main (void) {
    POINT p;
    p.x=0;p.y=0;p.z=3;
    Base A;
    Base B(p, p, "Unique");
    printf("A.pos.z is %d and B.pos.z is %dn", A.getPos().z, B.getPos().z);
    B.changeParent(A);
    printf("B.parent.pos.z %d should equal 0n", B.parent->getPos().z);
我得到的错误代码是:错误C2248: 'Base::parent':不能访问在'Base'类中声明的受保护成员另外,如果我把所有的东西都公开,它会编译得很好,但是在运行时它会崩溃。

注意:我没有复制所有的代码,只复制了我认为相关的部分。

编辑:完全转储错误:

(152) : error C2248: 'Base::parent' : cannot access protected member declared in class 'Base'
    (20) : see declaration of 'Base::parent'
    (18) : see declaration of 'Base'

This

printf("B.parent.pos.z %d should equal 0n", B.parent->getPos()

引发错误,因为

protected:
  Base* parent;

您试图从类实现外部引用B.parent。因为parent被声明为protected,它在这里是不可用的。在Base的声明中,您应该添加一个返回父类并且是公共的访问器函数,如:

public:
  inline Base* getParent() { return parent; }

如果你告诉我们哪一行有错误总是有帮助的。如果你提到是这一行,你现在已经有10个答案了。

printf("B.parent.pos.z %d should equal 0n", B.parent->getPos().z);

int main()不能访问Base的受保护成员,因此也不能访问B.parent。将其替换为:

printf("B.getParent().pos.z %d should equal 0n", B.getParent()->getPos().z);

http://ideone.com/CobdS还要注意,getParent()应该返回一个指针(Base*),而getChildren()应该返回const std::vector<Base*>&