현재 계층 구조의 일종을 구현 중이고 자식이 부모에 연결되어 있으면 부모 엔터티를 자식에게 할당해야합니다. 부모 클래스의 friend
메서드를 사용하여이 문제를 해결할 수 있고 좋은 코딩 스타일이 될 수 있다면 제 질문이 있습니다.C++을 사용하는 계층 적 구조의 친구 메서드
class Node {
Node* parent;
Node() : parent(nullptr) { }
friend void attachChild(const Node& child) const;
friend void detachChild(unsigned long idx) const;
};
class ListNode : public Node {
std::vector<Node*> childs;
ListNode() : Node() { this->childs = {}; }
void attachChild(Node* child) const {
child->parent = this;
childs.push_back(child);
}
void detachChild(unsigned long idx) const {
child->parent = nullptr;
child.erase(child.begin() + idx)
}
};
class NodeOne : public Node {};
class NodeTwo : public Node {};
class NodeThree : public Node {};
그리고 마지막으로 짧은 코멘트를 : : 여기가 무슨 뜻인지 설명하는 짧은 예는 자녀와 부모가 같은 종류의 내 시나리오에있을 수있는 반면 아이 엔티티는 분명히 그냥 하나의 상위 엔티티를 가질 수있다.
. 비록 그것을 사용하지 않는 경우가 있지만, 귀하의 경우에는 setter/getter 기능을 갖는 것이 더 나을 수도 있습니다. 'Node' 클래스가'Parent' 클래스 내부의 private 내부 클래스가 될 수 없다면,'friend'를 사용하는 것은 괜찮은 해결책이 될 수 있습니다. –
노드와 부모는 항상 동일한 기본 클래스에 의존하며 둘 다 부모를 가질 수 있습니다 (예제 업데이트). 그게 도움이 되겠습니까? – Phidelux