在抛出 std::string 实例后终止调用

Terminate called after throwing an instance of std::string

本文关键字:终止 调用 实例 string std      更新时间:2023-10-16

我正在尝试确定用户实例化的变量是否存在于方程中。我有这样的声明类:

#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

并在下面实现实例化变量:

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) {}

见 https://stackoverflow.com/a/2522311/1689451

相关文章: