这几天都在写编译器,打算用c++写,其中也遇到了很多问题
尤其今天下午的代码把我逼的,不禁想说几句粗话
在类中,我想定义几个static const * Word const成员,初始化遇到了很多的问题
定义的类如下
#ifndef _WORD_H
#define _WORD_H
#include <iostream>
#include "Token.h"
#include "Tag.h"
using std::string;
namespace lexer{
class Word : public Token
{
public:
Word(string s, int tag): Token(tag), lexeme(s)
{
}
~Word(void);
public:
string GetLexeme() const;
string ToString() const;
bool Equals(Token *t) const;
private:
string lexeme ;
public:
static const Word * const and;
static const Word * const or;
static const Word * const eq;
static const Word * const ne;
static const Word * const le;
static const Word * const ge;
static const Word * const minus;
static const Word * const True;
static const Word * const False;
static const Word * const temp;
};
}
#endif
本想在main里做一些测试,没想到老是提示 类成员重定义,后来查了下才知道,类的静态成员变量不能在main中初始化,要定义在类相同的名称空间里面
于是呢,在Word.cpp修改了下代码,果然成功了,代码如下
#include <exception>
#include "Word.h"
using std::exception;
namespace lexer{
const Word * const Word::and = new Word("&&", Tag::AND);
const Word * const Word::or = new Word("||", Tag::OR);
const Word * const Word::eq = new Word("==", Tag::EQ);
const Word * const Word::ne = new Word("!=", Tag::NE);
const Word * const Word::le = new Word("<=", Tag::LE);
const Word * const Word::ge = new Word(">=", Tag::GE);
const Word * const Word::minus = new Word("minus", Tag::MINUS);
const Word * const Word::True = new Word("True", Tag::TRUE);
const Word * const Word::False = new Word("False", Tag::FALSE);
const Word * const Word::temp = new Word("t", Tag::TEMP);
Word::~Word(void)
{
}
string Word::GetLexeme() const
{
return lexeme;
}
string Word::ToString() const
{
return lexeme;
}
bool Word::Equals(Token *t) const
{
if(typeid(*this) == typeid( *t) )
{
try{
Word* n = dynamic_cast<Word*>(t);
string src = this->GetLexeme();
if( src.compare(n->GetLexeme()) == 0)
return true;
}catch(exception e)
{
return false;
}
}
return false;
}
}