Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing values for a struct within a class

Tags:

c++

class

struct

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;
}
like image 406
Julie Rosen Avatar asked Feb 04 '26 05:02

Julie Rosen


1 Answers

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;
}
like image 79
Grant Peters Avatar answered Feb 05 '26 18:02

Grant Peters