我實在想不通,爲什麼我得到這些錯誤:無法轉換從「常量節點」「這個」指針「節點」
- 錯誤1個錯誤C2662:「無效節點:: setInfo(const型&)」 :不能轉換 'const的節點這個' 從指針'到 '節點&'
- 錯誤2錯誤C2662:「無效節點:: setLink(節點*):不能轉換
'this'從'const Node'指向'節點&'
這是我正在做的程序。
頭文件:
#pragma once
#include <iostream>
using namespace std;
template <class Type>
class Node
{
private:
Type info;
Node<Type> *link;
public:
// Constructors
Node();
Node(const Type& elem, Node<Type> *ptr);
Node(const Node<Type> &otherNode);
// Destructor
~Node();
// Mutators and Accessors (getters and setters)
void setInfo(const Type& elem);
Type getInfo() const;
void setLink(Node<Type> *ptr);
Node<Type> * getLink() const;
// Overload the assignment operator
const Node<Type> & operator=(const Node<Type>&);
};
template <class Type> Node<Type>::Node()
{
link = NULL;
}
template <class Type> Node<Type>::Node(const Type& elem, Node<Type> *ptr)
{
info = elem;
link = ptr;
}
template <class Type> Node<Type>::Node(const Node<Type> &otherNode)
{
otherNode.setInfo(info); //ERROR 1
otherNode.setLink(link); // ERROR 2
}
template <class Type> Node<Type>::~Node()
{
// fill in this
}
template <class Type> void Node<Type>::setInfo(const Type& elem)
{
info = elem;
}
template <class Type> Type Node<Type>::getInfo() const
{
return info;
}
template <class Type> void Node<Type>::setLink(Node<Type> *ptr)
{
link = ptr;
}
template <class Type> Node<Type> * Node<Type>::getLink() const
{
return link;
}
template <class Type> const Node<Type> & Node<Type>::operator=(const Node<Type>& n)
{
info = n.info;
link = n.link;
}
主文件:
include "Node.h"
#include <string>
#include <iostream>
using namespace std;
int main()
{
Node<string> *node1 = new Node<string>();
node1->setInfo("Hello");
Node<string> *node2 = new Node<string>("Hello World!", node1);
Node<string> *node3 = new Node<string>(*node2);
Node<string> *node4 = new Node<string>();
node4->setInfo("Foo Bar");
node4->setLink(node3);
cout << node3->getLink()->getInfo() << endl; // should return "hello world"
system("pause");
return 0;
}
非常感謝你,它現在有效。我找不到另一種寫法。 – TheSpider
@ user3593832 - 如果這是它所要做的,則不需要您編寫複製構造函數。看到我對你任務操作員的回答。 – PaulMcKenzie