【问题标题】:Struct and functions with templates带有模板的结构和函数
【发布时间】:2020-05-13 23:08:44
【问题描述】:

我刚开始使用模板,想在我的头文件中以这种方式实现它,但是我遇到了各种错误,不明白为什么。

头文件:

#ifndef EXAM3_H_
#define EXAM3_H_

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

const int maxInt = 2147483647;

template <typename T>

struct nodeType {
    T data;
    nodeType *next;
};

bool search(nodeType *head, const T &searchItem);
void deleteNode(nodeType *&head, nodeType *&tail, int &count, const T &deleteItem);
void initializeList(nodeType *&head, nodeType *&tail, int &count);
bool isEmptyList(const nodeType *head);
void printList(nodeType *head);
int lengthList(nodeType *head);
void destroyList(nodeType *&head, nodeType *&tail, int &count);
void insert(const T &newItem, nodeType *&head, nodeType *&tail, int &count);

#endif

错误:

【问题讨论】:

    标签: c++ templates struct


    【解决方案1】:

    我想你忘了输入class list 或类似的东西

    #ifndef EXAM3_H_
    #define EXAM3_H_
    
    #include <iostream>
    #include <fstream>
    #include <iomanip>
    #include <string>
    
    using namespace std;
    
    const int maxInt = 2147483647;
    
    template <typename T>
    class list{
    public:    
        struct nodeType {
            T data;
            nodeType *next;
        };
    
        bool search(nodeType *head, const T &searchItem);
        void deleteNode(nodeType *&head, nodeType *&tail, int &count, const T &deleteItem);
        void initializeList(nodeType *&head, nodeType *&tail, int &count);
        bool isEmptyList(const nodeType *head);
        void printList(nodeType *head);
        int lengthList(nodeType *head);
        void destroyList(nodeType *&head, nodeType *&tail, int &count);
        void insert(const T &newItem, nodeType *&head, nodeType *&tail, int &count);
    };
    #endif
    

    但是如果函数不是成员函数,那就错了,所以写出来,如下

    template<typename T>
    bool search(nodeType <T> *head, const T &searchItem);
    template<typename T>
    void deleteNode(nodeType <T> *&head, nodeType <T> *&tail, int &count, const T &deleteItem);
    template<typename T>
    void initializeList(nodeType <T> *&head, nodeType <T> *&tail, int &count);
    template<typename T>
    bool isEmptyList(const nodeType <T> *head);
    template<typename T>
    void printList(nodeType <T> *head);
    template<typename T>
    int lengthList(nodeType <T> *head);
    template<typename T>
    void destroyList(nodeType <T> *&head, nodeType <T> *&tail, int &count);
    template<typename T>
    void insert(const T &newItem, nodeType <T> *&head, nodeType <T> *&tail, int &count);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      • 2014-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多