c++ - 解析、词法分析、C++ 内存错误

标签 c++ parsing memory-management data-structures lnk2019

<分区>

下面是我执行词法分析的代码。我有几个请求。

  • 我收到 LNK2019 错误。 LNK2019 未解析的外部符号 “公共(public):__thiscall Stack::Stack(void)” (??0?$Stack@UToken@LexicalAnalysis@@@@QAE@XZ) 在函数中引用 “公共(public):__thiscall LexicalAnalysis::LexicalAnalysis(void)” (??0LexicalAnalysis@@QAE@XZ)。我认为它与 tokens 变量以及它在构造函数中的构造方式有关。我不确定。

  • 请检查我的代码,看看我是否正确管理内存,并且
    看看我最初解决问题的方法是否正确。

-

// Stack.h
#pragma once

#include <iostream>
#include <string>

using namespace std;

template <typename T>
class Stack
{
public:
    // Constructors
    Stack();
    Stack(const Stack<T>& rhs);
    Stack(Stack<T>&& rhs);

    // Destructor
    ~Stack();

    // Helper Functions
    inline int getSize() const
    {
        return size;
    }

    // Is the stack empty, no memory
    inline bool isEmpty()
    {
        return (size == 0) ? true : false;
    }

    // Add an element to the stack
    inline void push(const T& value) 
    {
        if (size == capacity) 
        {
            capacity = capacity ? capacity * 2 : 1;

            T* dest = new T[capacity];

            // Copy the contents of the old array into the new array
            copy(data, data + size, dest);

            delete[] data;

            data = dest;
        }

        // Stack size is increased by 1
        // Value is pushed
        data[size++] = value;
    }

    // Add an element to the stack (rvalue ref) IS THIS RIGHT??
    inline void push(const T&& value)
    {
        if (size == capacity)
        {
            capacity = capacity ? capacity * 2 : 1;

            T* dest = new T[capacity];

            // Copy the contents of the old array into the new array
            copy(data, data + size, dest);

            delete[] data;

            data = dest;
        }

        // Stack size is increased by 1
        // Value is pushed
        data[size++] = value;
    }

    // Remove an element from the stack
    inline const T& pop()
    {
        if (size > 0)
        {
            T value;

            size--;

            value = data[size];

            T* dest = new T[size];

            // Copy the contents of the old array into the new array
            copy(data, data + (size), dest);

            delete[] data;

            data = dest;

            return value;
        }

        return NULL;
    }

    // Search stack starting from TOP for x, return the first x found

    T& operator[](unsigned int i)
    {
        return data[i];
    }

    T operator[](unsigned int i) const
    {
        return data[i];
    }

private:
    T* data;

    size_t size, capacity;
};

// Stack.cpp
#include "Stack.h"

// Constructor
template <typename T>
Stack<T>::Stack()
{
    data = nullptr;

    size = 0;
    capacity = 0;
}

// Copy Constructor
template <typename T>
Stack<T>::Stack(const Stack<T>& rhs)
{
    this->size = rhs.size;
    this->capacity = rhs.capacity;

    this->data = new T[size];

    for (int i = 0; i < size; i++)
    {
        data[i] = rhs.data[i];
    }
}

// Move Constructor
template <typename T>
Stack<T>::Stack(Stack<T>&& rhs)
{
    this->size = rhs.size;
    this->capacity = rhs.capacity;
    this->data = rhs.data;

    rhs.data = nullptr;
}

// Destructor
template <typename T>
Stack<T>::~Stack()
{
    delete[] data;
}

// LexicalAnalysis.h
#pragma once

#include <iostream>
#include <string>

#include "Stack.h"

#define NUM_KEYWORDS 3
#define NUM_REL_OP 6
#define NUM_OTHER_OP 2

using namespace std;

class LexicalAnalysis
{
public:
    // Constructor
    LexicalAnalysis();

    // Destructor
    ~LexicalAnalysis();

    // Methods
    void createTokenStack(const string& inputString);

    inline bool isAlpha(const char& ch) const
    {
        int asciiVal = ch;

        if (((asciiVal >= 65) && (asciiVal <= 90)) ||
            ((asciiVal >= 97) && (asciiVal <= 122)))
            return true;

        return false;
    }

    inline bool isWord(const string& str) const
    {
        if (str.length() > 1)
            return true;

        return false;
    }

    inline bool isDigit(const char& ch) const
    {
        int asciiVal = ch;

        if ((asciiVal >= 48) && (asciiVal <= 57))
            return true;

        return false;
    }

    inline bool isRelationalOperator(const char& ch) const
    {
        if (ch == '=' || ch == '<' || ch == '>')
            return true;

        return false;
    }

    inline bool isOtherOperator(const char& ch) const
    {
        if (ch == ',' || ch == '*')
            return true;

        return false;
    }

    inline void printTokenStack()
    {
        for (int i = 0; i < tokens->getSize(); i++)
        {
            cout << tokens[i][0].instance << endl;
        }
    }

private:
    enum TokenType {
        IDENTIFIER,
        KEYWORD,
        NUMBER,
        REL_OP,     // such as ==  <  >  =!  =>  =<
        OTHER_OP,   // such as , * 

        UNDEF,      // undefined
        EOT         // end of token
    };

    struct Token {
        TokenType tokenType;
        string instance;
    };

    Stack<Token>* tokens;

    // Methods
    void splitString(const string& inputString, Stack<string>& result);
};

// LexicalAnalysis.cpp
#include "LexicalAnalysis.h"

LexicalAnalysis::LexicalAnalysis()
{
    tokens = new Stack<Token>();
}


LexicalAnalysis::~LexicalAnalysis()
{
}

void LexicalAnalysis::splitString(const string& inputString, Stack<string>& result)
{
    const char delim[2] = { ',', ' ' };
    char* dup = strdup(inputString.c_str());
    char* token = strtok(dup, delim);

    while (token != NULL)
    {
            result.push(string(token));
            token = strtok(NULL, delim);
        }

        // ARE THESE DELETES NECESSARY?
        delete dup;
        delete token;
    }
}

// main.cpp
#include <iostream>
#include <string>

#include "LexicalAnalysis.h"

using namespace std;

int main(int argv, char* argc)
{
    LexicalAnalysis lex = LexicalAnalysis();

    lex.createTokenStack("GET id, fname, lname FROM employee WHERE id > 5");

    system("PAUSE");
}

最佳答案

问题是您在 cpp 文件中定义了 Stack 方法。所有模板代码都应该放在头文件中。

模板定义在使用时必须对编译器可用。所以将模板代码放在 stack.h 文件中,而不是放在 stack.cpp 中,链接错误就会消失。事实上,所有 stack.cpp 代码都应该在 stack.h 中,您可以完全摆脱 stack.cpp。

关于第二个问题,你的pop方法真的很奇怪。为什么要在 pop 上分配内存?只需减小大小,无需分配更多内存。

inline const T& pop()
{
    if (size == 0)
        throw std::runtime_error("stack underflow");
    return data[--size];
}

关于c++ - 解析、词法分析、C++ 内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31733951/

相关文章:

ios - 插入数千条记录时 CoreData(swift) 内存问题

c++ - 用户定义的不同大小 vector 的减少

c++ - STL+内存管理问题

c++ - 没有合适的具有重载构造函数和继承的用户定义转换

c# - 使用 HTMLAgilityPack 解析 javascript HTML

python如何在不重复的情况下将新对象保存到列表中

c++ - 在sdl中显示移动对象

parsing - Julia 解析 CSV

go - 忽略 YAML 标签

c - 在C/C++程序中,如何为参数 vector 内存分配内存?