Hi, I'm just trying to write something simple up that will print out a polynomial.
Issue I'm having is, if I print out the list of Term objects within the default constructor for Poly, it'll work properly and print out whatever the dereferenced pointer is pointing at. However, when I try to move it to a void member function, it'll dereference the first Term object properly, and then proceed to print referenced addresses instead of the next Term object. I'm not sure if it's something I did when overloading the ostream operator to accept the Term objects or what, but it's rather frustrating. Was looking to see if someone could point me in the right direction.
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <string>
#include <list>
#include "poly.h"
#include "term.h"
int main() {
//initialize Poly/Term objects and add second Term object to linked list
Poly p(Term(4, 5));
p.add(Poly(Term(2,3)));
//test the member function method
p.print();
}
term.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#ifndef TERM_H
#define TERM_H
#include <iostream>
class Term {
public:
Term();
Term(int,int);
std::string get_term();
bool is_neg(int);
friend std::ostream &operator<<(std::ostream&, const Term&);
friendclass Poly;
private:
int co;
int exp;
};
#endif
If you want help then I suggest:
- putting everything in a single file (otherwise you are asking people to download 5 separate files)
- removing all extraneous material and keeping it simple.
The following may solve your immediate problem ... but not your ultimate design problem.
Fundamentally, a polynomial is just an array of coefficients (over a field).
1 2 3 4
void Poly::add(const Poly& t)
{
for ( auto &e : t.terms ) terms.push_back(e);
}