Я пытаюсь определить, присутствует ли переменная пользователя в уравнении. Я объявил класс следующим образом:
#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
Пожалуйста, попробуйте поймать постоянную ссылку,
catch(const string& ex) {}
Других решений пока нет …