Reputation: 245
if (polynomial1->get(0)->compareTo(polynomial2->get(0)) == 0)
{
polynomial1->get(0)->coefficient += polynomial2->get(0)->coefficient;
result->insert_tail->polynomial1->get(0);
}
Polynomial1
and Polynomial2
are both Linked Lists and I am adding polynomial terms together one node at a time. In my compareTo function if both the terms in the linked lists == 0 then I want access the coefficient and add the coefficient of both terms together. My problem is accessing the coefficient. I keep getting the error message:
class
Data
has no member named‘coefficient’
But my PolynomialTerm
class inherits Data
. Any help on accessing the coefficient?
class PolynomialTerm : public Data
{
public:
int coefficient;
Variable *variable;
PolynomialTerm(int coefficient, Variable *variable) :
coefficient(coefficient), variable(variable)
{ }
int compareTo(Data *other) const
{
PolynomialTerm * otherTerm = (PolynomialTerm*)other;
return variable->variableX == otherTerm->variable->variableX &&
variable->variableX == otherTerm->variable->variableX &&
variable->exponentX == otherTerm->variable->exponentX &&
variable->exponentY == otherTerm->variable->exponentY ? 0 :
variable->exponentX > otherTerm->variable->exponentX ||
variable->exponentY > otherTerm->variable->exponentY ? -1 : 1;
}
---edit--
here is also my Data class which is located in my header file.
class Data {
public:
virtual ~Data() {}
/**
* Returns 0 if equal to other, -1 if < other, 1 if > other
*/
virtual int compareTo(Data * other) const = 0;
/**
* Returns a string representation of the data
*/
virtual string toString() const = 0;
};
Upvotes: 0
Views: 729
Reputation: 11058
I suppose you're getting error here:
polynomial1->get(0)->coefficient
And (it's again my guess) this is because the get
function is defined in base class (Data
) and returns a pointer to Data
(not PolynomialTerm
). And of course Data
doesn't have coefficient
(only the PolynomialTerm
does).
The compiler doesn't know that the pointer returned by get
actually points to PolynomialTerm
instance. Hence you get the error.
One way of fixing this would be casting the pointer type to it's actual type PolynomialTerm*
:
dynamic_cast<PolynomialTerm*>(polynomial1->get(0))->coefficient
Upvotes: 1
Reputation: 57678
PolynomialTerm(int coefficient, Variable* variable):
coefficient(coefficient), variable(variable){}
Your compiler may be confused by coefficient(coefficient)
.
Change either the argument name or the member name:
PolynomialTerm(int coef, Variable* var):
coefficient(coef), variable(var){}
Upvotes: 0