0

我正在编写两个用于评估方程式中的表达式的类,即:方程式和表达式。Equation 类包含两个 Expression* 成员变量,需要使用它们来计算方程的右侧和左侧。为了解决他们如何访问每个持有的表达式(一个字符串)的问题,我为 Exression 类的构造函数创建了以下定义和实现:

#ifndef EXPRESSION_H
#define EXPRESSION_H
#include <string>

using namespace std;

class Expression
{
    private:
        int l, r;       

    public:
        Expression(string part);        
        string equationPart;


};
#endif



#include "Expression.h"
#include<cmath>
#include<iostream>
using namespace std;

Expression::Expression(string part)
{
    int len = part.length();
    equationPart[len];

    for(int i = 0; i < len; i++)
    {
        equationPart[i] = part[i];
    }   
}

我还为 Equation 类的实现编写了以下内容:

#ifndef EQUATION_H
#define EQUATION_H
#include "Expression.h"
#include <string>

using namespace std;

class Equation
{
    public:
        Equation(string eq);
        ~Equation();
        int evaluateRHS();
        int evaluateLHS();
        void instantiateVariable(char name, int value);

    private:
        Expression* left;
        Expression* right;

};
#endif




#include "Equation.h"
#include<cmath>
#include<iostream>
#include<cstdlib>
#include<cstring>

using namespace std;

Equation::Equation(string eq)
{
    int length = eq.length();

    string l;
    string r;
    bool valid = false;
    short count = 0;

    for(int i = 0; i < length; i++)
    {
        if(eq[i] == '=')
        {
            valid = true;
            for(short j = i+1; j < length; j++)
            {
                r += eq[j];
            }

            for(short j = i-1; j > 0; j--)
            {
                count++;
            }

            for(short j = 0; j < count; j++)
            {
                l += eq[j];
            }   
        }   
    }

    if(valid == false) 
    {
        cout << "invalid equation" << endl;
    }
    else if(valid == true)
    {
        left = new Expression(l);
        right = new Expression(r);
    }
}

当我运行如上所示的程序时,它会编译;但是当我尝试访问 Equation 中声明的左右 Expression 对象的字符串成员变量时,如下所示:

void Equation::instantiateVariable(char name, int value)
{
    string s1 = left.equationPart; 
    string s2 = right.equationPart; 

    short length1 = s1.length();
    short length2 = s2.length();

    bool found1 = false;

    for(short i = 0; i < length1; i++)
    {
        found1 = true;
        if(left.equationPart[i] == name)
        {
            left.equationPart[i] = itoa(value);
        }          
    }

    //and so on...
}

我最终得到一个编译器错误:

error: request for member 'equationPart' in '((Equation*)this)->Equation::left', which is of non-class type 'Expression*'

仅在 instantiateVariable 函数中,此错误就会多次出现。任何帮助或建议将不胜感激。

4

2 回答 2

1

left和都是指针,因此您需要通过 访问它们right,例如:Expressionoperator->

string s1 = left->equationPart; 
于 2012-10-02T20:23:08.647 回答
1

“left”是一个指针,用“->”访问。改“左”。到“左->”

于 2012-10-02T20:21:51.787 回答