c++ - 函数在某处被重新定义,我看不到我在哪里做
问题描述
我收到此错误,我无法弄清楚有人可以帮助解释我做错了什么吗?我尝试删除一些包含语句以及为我的项目创建一个生成文件,但我不断收到相同的错误
这是我的 Token.h
#pragma once
#include <string>
#include <iostream>
enum TokenType {
// Reserved Words:
VOID_TOKEN, MAIN_TOKEN, INT_TOKEN, COUT_TOKEN
};
// IMPORTANT: The list above and the list below MUST be kept in sync.
const std::string gTokenTypeNames[] = {
"VOID", "MAIN", "INT", "COUT"
};
class TokenClass {
private:
TokenType mType;
std::string mLexeme;
public:
TokenClass();
TokenClass(TokenType type, const std::string &lexeme);
TokenType GetTokenType() const {
return mType;
}
};
这是我的 Token.cpp 文件
#include "Token.h"
TokenClass::TokenClass() {
}
TokenClass::TokenClass(TokenType type, const std::string &lexeme) {
mType = type;
mLexeme = lexeme;
}
TokenType TokenClass::GetTokenType() const {
return mType;
}
这是我的 Main.cpp 文件
#include "Token.h"
int main() {
TokenType tt = VOID_TOKEN;
std::string lexeme = "void";
TokenClass tok1(tt, lexeme);
// std::cout << tok1 << std::endl;
}
这是我得到的错误
g++ -std=c++11 -g main.cpp Token.cpp -o Token
Token.cpp:11:11: error: redefinition of ‘TokenType TokenClass::GetTokenType() const’
TokenType TokenClass::GetTokenType() const {
^~~~~~~~~~
In file included from Token.cpp:1:
Token.h:40:12: note: ‘TokenType TokenClass::GetTokenType() const’ previously defined here
TokenType GetTokenType() const {
^~~~~~~~~~~~
make: *** [Makefile:8: main] Error 1
解决方案
您的错误消息告诉您每个文件中的文件名和行。CPP 的第 11 行和头文件的第 40 行。
{}
删除头文件中 thr=e 函数的主体(里面的东西)部分)用 a 重新包装;
),或者删除 cpp 文件中所有提到的函数。两者都有效。