给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。
案例:简谱到音乐的转译(音乐简谱中描绘乐曲用的是1234567,而实际发出的声音却是"哆瑞咪发嗦啦西")。
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
// 待解释文本
class PlayContext
{
public:
string get_text()
{
return this->m_text;
}
void set_text(string text)
{
this->m_text = text;
}
private:
string m_text;
};
// 文法表达式接口
class Expression
{
public:
virtual void excute(PlayContext* context) = 0;
};
// 音符类,进行具体的音符转换
class Note : public Expression
{
public:
void excute(PlayContext* context)
{
string s = context->get_text();
string buf;
if (context->get_text().length() == 0)
{
return;
}
else
{
vector<string> vec;
stringstream ss(context->get_text());
while (ss >> buf)
vec.push_back(buf);
vector<string>::iterator it;
for (it = vec.begin(); it != vec.end(); it++)
{
int c = stoi(*it);
switch (c)
{
case 1:
cout << "do" << endl;
break;
case 2:
cout << "re" << endl;
break;
case 3:
cout << "mi" << endl;
break;
case 4:
cout << "fa" << endl;
break;
case 5:
cout << "so" << endl;
break;
case 6:
cout << "la" << endl;
break;
case 7:
cout << "xi" << endl;
break;
}
}
}
}
};
void test_01()
{
PlayContext* context = new PlayContext;
Expression* note = new Note;
context->set_text("3 5 6 3 5");
note->excute(context);
context->set_text("6 5 3 1 2");
note->excute(context);
delete context;
delete note;
}
int main()
{
test_01();
system("pause");
return 0;
}