vendredi 20 décembre 2019

Is there a library that check the type of variables in C++?

I have the following class:

class ComplexNumber
{
    public:
        ComplexNumber();
        ComplexNumber(const float &RealPart, const float &ImaginaryPart);
        ComplexNumber(const ComplexNumber &NewComplexNumber);
        ~ComplexNumber(); // useless
        void SetRealPart(const float &RealPart);
        void SetImaginaryPart(const float &ImaginaryPart);
        friend ComplexNumber operator+(const ComplexNumber &Complex1, const ComplexNumber &Complex2);
        friend ComplexNumber operator-(const ComplexNumber &Complex1, const ComplexNumber &Complex2);
        friend std::ostream & operator<<(std::ostream &output, const ComplexNumber &NumberToDsiplay);
        friend std::istream & operator >>(std::istream &input, ComplexNumber &NumberToInput);
        bool operator==(const ComplexNumber &Complex) const;
        bool operator!=(const ComplexNumber &Complex) const;

    private:
        float RealPart;
        float ImaginaryPart;
};

My question is about this operator overloaded: friend std::istream & operator >>(std::istream &input, ComplexNumber &NumberToInput);

Here is the implementation:

std::istream & operator >>(std::istream &input, ComplexNumber &NumberToInput)
{
    std::cout << "Enter the real part: ";
    input >> NumberToInput.RealPart;
    std::cout << "Enter the imaginary part: ";
    input >> NumberToInput.ImaginaryPart;
}

If, instead of input a float, I input a string or whatever type, I get a weird behaviour.

How can I handle that?

How can I handle that with templates?

Aucun commentaire:

Enregistrer un commentaire