I have the following code in the private section of a basic Polynomial class .h file:
private:
struct Term
{
float coefficient;
int power; // power of specific term
};
int degree; //total number of terms
I have the following default constructor for the Polynomial class:
Polynomial::Polynomial()
{
Polynomial.Term poly;
poly.power = 0;
poly.coefficient = 0;
degree = 1;
}
I am confused on how to access the terms inside the struct as well as the variable outside the struct. I tried to google this, but couldn't find anything helpful.
Edit: overloaded output operator code
ostream & operator << (ostream & outs, Polynomial & P)
{
outs << P[0].poly.coefficient << "x^" << P[0].poly.power;
for (int i=1; i<P.degree-1; i++)
{
if (P[i].poly.coefficient > 0)
outs << "+";
outs << P[i].poly.coefficient << "x^" << P[i].poly.power;
}
outs << endl;
}
You've declared the variable within the constructor function. Once execution leaves the constructor, that variable is destroyed. Instead, you need to add the variable to the class declaration. If you want to be able to access the members from outside any of the class functions, you'll also need to make the variables and struct definition public.
class Polynomial
{
public:
struct Term
{
float coefficient;
int power; // power of specific term
};
Term poly;
int degree; //total number of terms
Polynomial();
};
Polynomial::Polynomial()
{
poly.power = 0;
poly.coefficient = 0;
degree = 1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With