来自Bjarne Stroustrup的编程原理和练习,c 第7章练习4:
" get_value((,set_value((,is_declared((和define_name((函数所有函数都在变量var_table上操作。定义一个称为symber_table的类,该类称为syngr_table,具有类型vector and emborm function and Member函数get((,set(set(set(set(set(((,is_declared和nectare((。重写计算器以使用symber_table类型的变量。"
class Variable {
public:
string name;
double value;
bool var; // variable (true) or constant (false)
Variable(string s, double d, bool b) :name(s), value(d), var(b) { }
private:
};
class Symbol_table {
public:
double get(string s);
void set(string s, double d);
bool is_declared(string var);
double declare(string s, double val, bool var = true); //default is variable
private:
vector<Variable> var_table;
};
double Symbol_table::get_value(string s) {
// return the value of the Variable names s
for (Variable& v : var_table) {
cout << "getting variable: " << v.name << " " << v.value << " " << v.var << endl;
if (v.name == s) {
return v.value;
}
}
error("get: undefined variable ", s);
}
基本上,变量被分配一个名称,值,并且在那里确定它是常数还是变量。所有变量均通过symber_table :: excrare((声明,并将其放入向量var_table中。symnd_table :: get_value((应该读取具有特定名称的变量的值。
每当我使用symber_table :: get_value((时,我总是会遇到错误,它永远不会成功返回v.value。为什么?我该如何解决?
您应该检查勘误 - 其中包括练习4:
的更正s/extare_name((/define_name((/
(Bjarne在其网站上出版了所有书籍的Errata。(
类Symbol_table
中的成员函数称为double get(string s);
,但实际上将其定义为double Symbol_table::get_value(string s)
double Symbol_table::get(string s) { //instead of get_value(string s)