static const * const 类成员 初始化

这几天都在写编译器,打算用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;

}

 

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值