Stream Operator Overload Problem

I have a class that uses operator overloading, but there are some warnings.

// base.h

class base {
public:
    base();
    base(int n);
    virtual ~base();
    virtual void printBase(std::ofstream & out);
    virtual base & operator =(const base &);
    friend std::ofstream & operator <<(std::ofstream & out, const base &);
private:
       double * coeff;
       int n;
};

// base.cpp

std::ofstream & operator<<(std::ofstream & fout, const base & obj)
{
    for(int i =0; i<(obj.n)-1; i++)
    {
        fout << obj.coeff[i]<<"*x"<<i;
        if(i<obj.n-2)
        {
            fout<<"+";
        }
    }
    fout<<"="<<obj.coeff[(obj.n)-1];
    return fout;
}

void base::printBase(std::ofstream & fout)
{
    for(int i =0; i<n-1; i++)
    {
        fout<<coeff[i]; // warning occurs here!!
        if(i<n-2)
        {
            fout<<"+";
        }
    }
    fout<<"="<<coeff[n-1];
}

Warning:

<P →
 warning: ISO C++ says that these are ambiguous, even though the worst conversion for
 the first is better than the worst conversion for the second:
    c:\wascana\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/ostream.tcc:105:5: note:
 candidate 1: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(int) [with _CharT = char, _Traits = std::char_traits<char>]
    ..\Hyperplane.cpp:55:17: note: candidate 2: std::ofstream& operator<<(std::ofstream&, const Hyperplane&)

From the above warning there should be a problem <<. I know the reason, but how can I handle this warning?

Thank!

+3
source share
1 answer

The problem is actually related to one of your class constructors:

base(int n);

This constructor is what is called a conversion constructor. It can be used to convert intto base, so it will be legal:

base x = 42;

If you do not want to allow this implicit conversion, you can do the constructor explicit:

explicit base(int n);

: " fout << coeff[i];?

, ( , "" ): - std::ostream operator<< , :

std::ostream& operator<<(std::ostream&, double);

- , :

std::ofstream& operator<<(std::ofstream&, const base&);

: std::ofstream std::ostream . , a double, .

std::ofstream. double to int, int base.

, , , , .

, , .

, , :

std::ostream& operator<<(std::ostream&, const base&);
+9

Source: https://habr.com/ru/post/1788373/


All Articles