부모님/자식 관계를 만드는 데 문제가 있습니다. 이 방법을 설명 할 수있는 가장 쉬운 방법은 동일한 유형의 다른 객체에 대한 참조 (또는 포인터)를 가진 객체와 더 많은 객체에 대한 자식 참조 (또는 포인터)의 배열을 가지는 것입니다. 개체에는 .getChildren, .addChild, .removeChild, .getParent, .changeParent와 같은 기능이 있어야합니다. 포인터에 대해 끔찍한 시간을 보냈습니다. 누구든지 코드가 도움이된다면 도움이 될 것입니다. 또한 호기심이 생길 경우 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 %d\n", A.getPos().z, B.getPos().z);
B.changeParent(A);
printf("B.parent.pos.z %d should equal 0\n", B.parent->getPos().z);
나는 코드를 얻을 오류가 있습니다 : 오류 C2248 : '자료 : 부모', 또한 클래스 '자료'에 을 선언 보호 된 멤버에 액세스 할 수 없습니다 나는 모든 것을 공개 할 경우 , 그것은 잘 컴파일 될 것이지만, 그 다음에는 실행 중에 충돌합니다.
참고 : 모든 코드를 복사하지 않았으며 관련성이 있다고 생각합니다.
편집 : 오류의 전체 덤프 :
(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-> stuff 대신 생성자에 대해 [초기화 목록] (http://www.cprogramming.com/tutorial/initialization-lists-c++.html)을 사용해야합니다. 그러면 복사본이 저장됩니다. –
덤프가있는 수정 된 게시물. 나는 그것들을 이해하지 못한다. 나는 그저 오래 전에 그렇게 읽은 사람들에 대해 읽었으므로 나는 아직 그것에 대해 걱정하지 않는다. – Hondros
또한, "public"으로 변경했지만 런타임시 충돌이 발생하면 컴파일 할 것이므로 실제로 언어가 잘못되어 있다고 생각하지 않습니다. – Hondros