Polynomial Class
File: poly.h
/* * Simple polynomial class */ #ifndef _poly_h_ #define _poly_h_ #include <vector> #include <string> #include <algorithm> #include <initializer_list> using namespace std; class Polynomial { public: // Various constructors. Polynomial(double c = 0.0) { m_coeff.push_back(c); } Polynomial(double A1, double A0) { m_coeff = { A0, A1 }; normalize(); } Polynomial(double A2, double A1, double A0) { m_coeff = { A0, A1, A2 }; normalize(); } Polynomial(const initializer_list<double> &il) { m_coeff = il; reverse(m_coeff.begin(), m_coeff.end()); normalize(); } // Set the coefficient for the exponent exp (exp >= 0). void set_coeff(double c, int exp) { if(m_coeff.size() < exp+1) m_coeff.resize(exp+1,0.0); m_coeff[exp] = c; } // Return the order of the polynomial int order() const { return m_coeff.size() - 1; } // Evaluate the polynomial at x. double f(double x) const; // Return the first derivative. Polynomial dx() const; // Create a string for printing. This is actually the most // complicated method. Printing for humans often is; they just don't // think like computers. string tos() const; private: // Private constructor used to build an object from a // vector of coefs, emptying the argument object. Polynomial(vector<double> &values) { m_coeff.swap(values); } // Get rid of leading zeros. void normalize(); // Polynomial coefficients, starting from the constant and // increasing order. vector<double> m_coeff; }; #endif

The more complete way to store a class is in two files, one an .h file containing the class itself, and another containing the bodies of larger functions. The files are conventionally given the same name stem with extensions .h and .cpp.

Notice how some of the methods are given only prototypes. The bodies of those functions are contained in the file poly.cpp.

There could be any number of files using the class, with any number of names, usually .cpp type.

Also note the constructor which takes initializer_list<double>. That is a list of doubles enclosed in curly braces.