0

I have two classes Polynom and Fraction.

I need to do a template for Polynom, for using Fraction like coefficient in Polynom, like: 3/4 x^0 + 5\6 x^1 etc.

I understood how to use a simple type like double or int, but how to get this to work for a class I have no idea, and can't find a material on this theme.

class Fraction {
private:
    int numerator, denominator;
public:
    Fraction();
    Fraction(int, int);
    Fraction(int);
}
template<class T>
class PolynomT {
private:
    int degree;
    T *coef;
public:
    PolynomT();
    explicit PolynomT(int, const T * = nullptr);
    ~PolynomT();
};

template<class T>
PolynomT<T>::PolynomT(int n, const T *data): degree(n) {
    coefA = new T[degree+1];
    if (data == nullptr) {
        for (int i = 0; i < degree+1; ++i)
            coefA[i] = 0.0;
    }
    else {
        for (int i = 0; i < degree + 1; ++i)
            coefA[i] = data[i];
    }
}

/*Problem here*/

int main() {

    PolynomT<Fraction> a(); // what need to pass on here in arguments?
                            // how should the constructor look like?
    /*Example*/
    PolynomT<Fraction> b(); 

    PolynomT<Fraction> c = a + b; // or something like this.
}

So, how to do the class constructor for Fraction in PolynomT, and how to do overloading operators for this?

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
Hiroyasu
  • 83
  • 1
  • 6
  • Please clarify the `data == nullptr` case. Assigning `coefA[i] = 0.0;` may not work for user defined data types. For `Fraction` class, it might work. But I don't think this is a very general way to do this. – Kunal Puri May 15 '19 at 05:29
  • Notice that `PolynomT a();` is a function declaration (vexing parse). it should be `PolynomT a;` or `PolynomT a{};` – Jarod42 May 15 '19 at 08:26

1 Answers1

2

The problem with the coefA[i] = 0.0 assignment in the PolynomT constructor happens because Fraction does not have a constructor that takes a double, nor does it have an assignment operator that takes a double. There are several possible solutions.

Change from raw memory management to std::vector for coefA.

std::vector<T> coefA;
// Then resize appropriately in the constructor

This would automatically fill all the elements with a default constructed object, so you wouldn't need to do anything if data == nullptr.

Another possibility is to change the assignment to

coefA[i] = T();

This will assign a default constructed object of the type (0.0 for doubles).

What are the basic rules and idioms for operator overloading has detailed information on overloading operators.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56