我正在尝试将一个字符序列传递给一个链表,但是这个错误出现在我身上,我不知道它可能是什么。 无法将'Type'转换为'const ChainNode'
这里是我所拥有的:
#include <iostream>
using namespace std;
template <class Type> class Chain;
template <class Type> class ChainNode;
template <class Type>
class Stack
{
friend class Chain <Type>;
public:
Stack(int MaxStackSize = DefaultSize);
//~Stack();
bool Full();
bool Empty();
Type& Top();
void Push(const Type& item);
Type Pop(Type&);
void Print();
void Read(char x[], int size, Chain <Type> input_chain);
private:
int MaxSize;
int top;
Type* stack;
char a;
};
我在此函数上遇到问题,其目的实际上并不重要,因为该错误与算法无关,与C ++类的参数有关。
template <class Type>
void Stack<Type>::Read(char x[], int size, Chain <Type> input_chain) {
int count = 0;
for (int i = 0; i < size; i++)
{
count++;
if (Empty()) {
if (x[i] == '+' or x[i] == '*') {
Push(x[i]);
break;
}
else{
cout << x[i];
input_chain.attach(x[i]); //<-- Here is the problem
}
}
}
//Node of the chain declaration
template <class Type>
class ChainNode
{
friend class Stack <Type>;
friend class Chain <Type>;
public:
ChainNode() {};
//~ChainNode();
private:
Type character;
ChainNode* link;
};
错误与此类的void函数有关:
//Chain class declaration
template <class Type>
class Chain
{
friend class Stack <Type>;
friend class ChainNode <Type>;
public:
Chain() {
first = 0;
last = 0;
};
void attach(Type& k) {
ChainNode<Type>* newnode = new ChainNode<Type> (k);
if (first == 0) first = last = newnode;
else {
last->link = newnode;
last = newnode;
}
}
private:
ChainNode <Type> *first;
ChainNode <Type> *last;
};
这是我的主要功能:
int main() {
Stack <char> mystack(20);
Chain <char> mychain;
int const size = 20;
char math_infix[size];
int operators = 0;
int operands = 0;
int math_size = 0;
cout << "Write the math equation: " << endl;
cin >> math_infix;
for (int i = 0; i < size; i++)
{
if (i % 2 != 0 and (math_infix[i] == '+' or math_infix[i] == '*')) {
operators++;
}
}
operands = operators + 1;
math_size = operands + operators;
mystack.Read(math_infix, math_size, mychain);
//mystack.Print();
return 0;
}
抱歉,长代码。这是我遇到的麻烦,非常感谢您的帮助!
您需要在ChainNode
中提供一个转换构造函数,以使attach
中的以下行起作用:
ChainNode<Type>* newnode = new ChainNode<Type> (k);
您需要添加:
ChainNode(Type c) : character(c) {}
至您的ChainNode
类。