链接列表 C++ 错误(无法将 'Type' 转换为 'const ChainNode<Type>')

Linked lists C++ Error (Cannot convert 'Type' to 'const ChainNode<Type>')

我试图将一个字符序列传递给一个链表,但我遇到了这个错误,我不知道它是什么。

Cannot convert 'Type' to 'const ChainNode<Type>'

这是我的:

#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++ 上 classes 的参数。

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;
};

错误与此 class 上的 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 Class。