我收到一些源自我的复制构造函数的编译器错误。我知道第一个错误是由于操作数类型不兼容,我只是不确定编写该代码的更好方法。第二个错误我完全不确定。为什么不'='
能够从 Node* 转换为 Node* 吗?
任何帮助或指导将被appriciated。
谢谢!
// Copy-Constructor
List::List(const List& theList)
{
Node* tempPtr = new Node;
tempPtr = theList.first;
//error C2040: 'tempPtr' : 'List' differs in levels of indirection from 'Node *'
List(tempPtr);
while (tempPtr != NULL)
{
Node* copyNode = new Node;
//error C2440: '=' :cannot convert from 'Node *' to 'Node *'
copyNode = tempPtr;
tempPtr = tempPtr->getNext();
nodeListTotal++;
}
}
List::List():first(0), last(0), nodeListTotal(0)
{
}
// Destructor
List::~List()
{
Node* currentNode = first;
while(currentNode != NULL)
{
Node* temp = currentNode;
currentNode = currentNode->getNext();
delete temp;
}
}
最佳答案
这里有几个问题。一是C2040和C2440其中型号相同的型号。根据我的发现 in this discussion , 声明中允许使用括号,因此语句:
List(tempPtr);
List tempPtr;
tempPtr
,你给了它一个不同的类型。但请注意,如果您写的是 List*(tempPtr)
它会说 redefinition: different basic types
,所以它似乎也与 List
的事实有关。不像 Node*
那样是一个指针(这就是“间接级别”位的来源)。 C2440 发生是因为重新声明。您可以通过注释掉 List(tempPtr);
来确认这一点。并看到代码将编译。然而,它会编译的事实并不是说它在任何方面都是正确的。Node*
的构造函数,即使你有一个,那也不是正确的称呼方式。我不完全确定你想用它做什么。Node
像疯了一样的物体。当你执行这些行时:Node* tempPtr = new Node;
tempPtr = theList.first;
Node* copyNode = new Node;
copyNode = tempPtr;
Node
对象,然后扔掉指向它们的指针。如果您试图复制 Node
对象,这不是这样做的方法。你也需要一个复制构造函数。List
进入正确的复制构造函数的所有内容。类,但它涵盖了您发布的代码的一些最大问题,尤其是这似乎是您收到这两个错误的原因。
https://stackoverflow.com/questions/18175650/
相关文章:
android - 使用二进制文字数字时出错。为什么要使用旧的JDK?
wpf - 当应用程序类型为类库时,未定义的CLR namespace
c++ - KEIL错误: no instance of overloaded function “
compiler-errors - 错误在Centos6.4中更新lib.so.6文件
vba - Excel VBA : Compiler Errors
compiler-errors - 使用 Eclipse Android 编译 FFMPEG
ubuntu - 无法在Ubuntu 13.04中安装ARToolkit