我有结构 Node
和结构 UniqueInstructor
。两者都是单链表。我已经用一些值填充了 struct Node。现在我需要做的是用 Node 的结构特定值 (std::string instructor
) 填充第二个 UniqueInstructor 结构。
这是我的结构的样子:
// main struct that I already filled with data
struct Node {
Node* pNext;
std::string data1;
std::string data2;
std::string day;
std::string group;
std::string instructor; // these are the items I want to copy
// into the UniqueInstructor struct
std::string course;
};
// my 'target' struct, also linked list
struct UniqueInstructor {
UniqueInstructor* pNext;
std::string instructor;
};
现在,我需要做的就是将 Node
中的所有 std::string instructor
值复制到 UniqueInstructor
中。
我试过很多东西,例如:
void DuplicateInstructor(Node *&pHead)
{
pHead = new UniqueInstructor { pHead, pHead->instructor };
}
但我收到错误。在这种情况下:
无法在初始化中将“Node*”转换为“UniqueInstructor*”
我的问题可能在于将结构传递给该函数的某个地方。请原谅,我是结构和指针的新手。谢谢你的帮助。
最佳答案
您只需将 Node::instructor
字段复制到 UniqueInstructor::instructor
字段中。这两个字段都是 std::string
所以没问题。
void like_this(Node& n, UniqueInstructor& i)
{
i.instructor = n.instructor;
}
现在还不是很清楚您实际想要实现什么以及您的程序结构是什么,所以我无法告诉您在哪里或如何获得 Instructor
对象。在上面的示例中,两个对象都存在。此外,您不能将 Node
与 UniqueInstructor
链接起来。只是 Node::pNext
和 UniqueInstructor::pNext
是完全不同的类型,所以我不知道你想在这里做什么。
此外,显式调用 new
/delete
是一种非常糟糕的做法。它们在 C++ 中绝对没有位置(在库实现之外)。太让人头疼了,更重要的是,错误的空间太大了(异常时的内存泄漏)。请阅读 C++ 中的 RAII 和智能指针。
关于c++ - 无法将结构的项目复制到另一个结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53900694/