【问题标题】:Cant create object of type unorderedLinkedList无法创建 unorderedLinkedList 类型的对象
【发布时间】:2019-07-16 03:48:06
【问题描述】:

我有两个.h 文件,基类linkedListType 和派生类unorderedLinkedList。出于某种原因,它不会让我从我的 unorderedLinkedList 类中创建一个对象。我还在整个程序中使用模板。

#include <iostream>
#include "unorderedLinkedList.h"

using namespace std;

int main()
{
    unorderedLinkedList<int> list, subList;

    int num;

    cout << "Enter numbers ending with -999" << endl;
    cin >> num;
}
#pragma once
#define UNORDEREDLINKEDLIST_H
#ifndef UNORDEREDLINKEDLIST_H
#include "linkedList.h"
#include <iostream>
using namespace std;

//creates class type unorderedLinkedList
template <class Type>
class unorderedLinkedList : public linkedListType<Type>
{
public:
    bool search(const Type& searchItem) const;
    //function to determine wether searchItem is in the list
    void insertFirst(const Type& newItem);
};

#endif
#pragma once
#define LINKEDLISTTYPE_H
#ifndef LINKEDLISTTYPE_H
#include <iostream>
#include <cassert>
using namespace std;

template<class Type>
class linkedListType
{
public:
    void divideMid(linkedListType<Type>& sublist);
    // divide list
    const linkedListType<Type>& operator=(const linkedListType<type>&);
    // overload the assignment operator.
    void initializeList();
};

#endif

【问题讨论】:

  • 你先#define UNORDEREDLINKEDLIST_H,然后然后检查它是否未定义。当然它实际上是定义的——你刚刚在上面一行定义了它。于是整个标题被跳过。

标签: c++ undeclared-identifier


【解决方案1】:

在您的两个头文件中,您的 #define 和 #ifndef 语句的顺序错误。

在每个文件中,你定义了保护值,然后检查它是否被定义,它是什么,所以头文件的整个内容都被跳过了。

只有尚未定义的保护值才需要定义:

#ifndef UNORDEREDLINKEDLIST_H
#define UNORDEREDLINKEDLIST_H
...
#endif
#ifndef LINKEDLISTTYPE_H
#define LINKEDLISTTYPE_H
...
#endif

【讨论】:

    【解决方案2】:

    如上所述,您需要在定义之前检查包含保护是否已定义,否则它将永远不会包含在首位。

    您还应该使用#pragma once(如果支持)或#ifndef #define 保护。没必要同时使用。

    再次重申

    -删除#pragma 一次

    -更改 ifndef / define 的顺序

        #ifndef UNORDEREDLINKEDLIST_H
        #define UNORDEREDLINKEDLIST_H
        ...
        #endif
    
        #ifndef LINKEDLISTTYPE_H
        #define LINKEDLISTTYPE_H
        ...
        #endif
    

    【讨论】:

      猜你喜欢
      • 2020-11-09
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 2021-08-15
      • 2021-03-07
      相关资源
      最近更新 更多