gpt4 book ai didi

c++ - 如何不调用位于链表节点中的对象的构造函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:10:19 25 4
gpt4 key购买 nike

所以我有一个类,我们称它为 Cow。这头奶牛有一个年龄和一些其他变量,比如一个静态的 Cows alive 变量。

好吧,我想做一个链表,我为它做了类,链表类里面的节点结构,看起来有点像这样。

struct node{
Cow data;
node* next;
};

然后是我的 addNode 函数来添加一个节点。

void List::addNode(Cow newData)
{
//Creates a Cow object that will skew counters. BELOW.
node* n = new node;
n->data = newData;
n->next = NULL;
if(head == NULL){
head = n;
}else{
curr = head;
while(curr->next != NULL){
curr = curr->next;
}
curr->next = n;
}

}

随着行 node* n = new node,它将创建一个新的 Cow 对象,它调用 Cow 构造函数,该构造函数递增 Cows alive 静态变量的数量。

简单地说,我的问题是...第一次创建节点时,我将如何不调用该 Cow 对象的构造函数,以便我可以用 newData 对象填充它。因此,不要弄乱我的计数器,构造函数中的哪个增量?

最佳答案

您可以创建一个 node 构造函数,它接受一个 Cow 参数并使用它来复制构造其内部 Cow。我假设 Cow 的复制构造函数不会增加静态计数器。

struct node{
node(Cow &cow): data(cow) {}

Cow data;
node* next;
};

关于c++ - 如何不调用位于链表节点中的对象的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42744060/

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