我试图确定用户实例化的变量是否存在于等式中。我将类声明如下:
#ifndef EQUATION_H
#define EQUATION_H
#include "Expression.h"
#include "Shunt.h"
#include <string>
#include <map>
using namespace std;
class Equation
{
public:
Equation(string eq);//If an equation is invalid, throw an exception string
Equation(const Equation& other);
Equation& operator=(const Equation& other);
~Equation();
int evaluateRHS();//If at least one variable does not have a value, throw an exception string
int evaluateLHS();//If at least one variable does not have a value, throw an exception string
void instantiateVariable(char name, int value);//If does not exist in the equation, throw an exception string
int RHSdistanceFromLHS();//If at least one variable does not have a value, throw an exception string
string original;
map<char, int> variables;
private:
Expression* left;//Left side of the equals
Expression* right;//Right side of the equals
};
#endif
并在以下实现instantiateVariable:
void Equation::instantiateVariable(char name, int value)
{
short firstLen = left->equationPart.length();
short secLen = right->equationPart.length();
bool exists = false;
for(short i = 0; i < firstLen; i++)
{
if(left->equationPart[i] != name)
{
exists = false;
}
else
{
exists = true;
}
}
if(exists == false)
{
for(short i = 0; i < secLen; i++)
{
if(right->equationPart[i] != name)
{
exists = false;
}
else
{
exists = true;
}
}
}
if(exists == false)
{
string er = "error"; //Not caught successfully. Terminates entire program.
throw er;
}
variables[name] = value;
}
在主函数中调用时:
void testCase3()
{
try
{
Equation equation3("(y - (x + 3) ^ y) * 5 / 2 = log 20 - y");
equation3.instantiateVariable('z',3);
}
catch(string ex)
{
cout<<"Exception thrown"<<endl;
}
}
int main(int argc, char** argv)
{
testCase3();
}
发生以下错误:
terminate called after throwing an instance of 'std::string'
Aborted
答案 0 :(得分:1)