gpt4 book ai didi

c++ - 在有向图中复制多态对象的构造函数

转载 作者:太空宇宙 更新时间:2023-11-04 14:33:53 25 4
gpt4 key购买 nike

我有一个通用树的基类节点:

class Node {
public:
Node() {
parent = NULL;
name = "";
rule = NULLRULE;
childs = std::vector<Node*>();
};

void addChild(Node* child){
childs.push_back(child);
child->setParent(this);
};

void setParent(Node* p) {
this->parent = p;
}

virtual ~Node(){
if (childs.size() == 0) return;

// remove duplicate childs
// since we allow having same child.
std::sort(childs.begin(), childs.end());
childs.erase(std::unique(childs.begin(), childs.end()), childs.end());
for(unsigned int i = 0; i < childs.size(); i++) {
delete childs[i];
}
}

我派生类 NodeSquare、NodeCircle 等...所有节点在以下类中形成一棵树:

class Tree {
Tree() {};
~Tree() {
delete root;
};
void BFS(){};
etc...
Node* root;
}

如何为 Tree 类定义复制构造函数?我通过引用传递树,这就是为什么我需要一个复制构造函数......

processTree(Tree& t) {
t = Tree();
}

最佳答案

Tree(const Tree & copy)
{
if(copy != *this)
{
//to do
}

}

复制构造函数具有此签名,然后如果您像普通构造函数一样分配数据的范围,则该语句是为了安全,但您可以使用列表初始化器。

关于c++ - 在有向图中复制多态对象的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32277780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com