c++ - 复制构造函数 - 编译器错误 C2040 和 C2440

我收到一些源自我的复制构造函数的编译器错误。我知道第一个错误是由于操作数类型不兼容,我只是不确定编写该代码的更好方法。第二个错误我完全不确定。为什么不'='能够从 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); 来确认这一点。并看到代码将编译。然而,它会编译的事实并不是说它在任何方面都是正确的。

问题#2 是您没有在此处显示采用 Node* 的构造函数,即使你有一个,那也不是正确的称呼方式。我不完全确定你想用它做什么。

问题 #3 是您正在泄漏 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 “

java - 需要一个实例化类的方法被调用

compiler-errors - 错误在Centos6.4中更新lib.so.6文件

vba - Excel VBA : Compiler Errors

compiler-errors - 使用 Eclipse Android 编译 FFMPEG

ubuntu - 无法在Ubuntu 13.04中安装ARToolkit

java - 无法解析为类型-在RHEL 5上编译servlet(tomcat)时出错

c++ - Googletest 编译错误 : ‘xyzTest’ was not declared