I am working with Qt 5.10 and I have to subclass QDatastream and I overload the operator << with an other class, like this :
class myDataStream:public QDataStream
{
public :
myDataStream(QIODevice* device):QDataStream(device)
{}
};
class data
{
public:
data(double v):data_(v) {}
double getData() const {return data_;}
void record(myDataStream& stream) const;
private:
double data_;
};
void data::record(myDataStream &stream) const
{
stream<<getData();
}
myDataStream &operator<<(myDataStream &stream, const data &d )
{
stream<<d.getData(); //<------ Error here
return stream;
}
I have this error :
> error: use of overloaded operator '<<' is ambiguous (with operand types 'myDataStream' and 'double')
When I remove the const operator behind data like this :
myDataStream &operator<<(myDataStream &stream, data &d )
{
stream<<d.getData();
return stream;
}
I don't have error. The operator<< doesn't change the class data ... doesn' it ? the getData() method is const.
I don't understand.
Someone to help me ?
QDataStream, you should use composition or private inheritance — your class is not aQDataStreamanymore. Your stream operators can then be forwarding to QDS implementations as needed. The compiler is giving you a subtle hint about it. Of course there is a “fix” to the compiler error, but it only camouflages the fundamental design bug you have. - Kuba hasn't forgotten Monicaoperator<<to use theQDataStreamimplementation when appropriate. So the public inheritance buys you nothing here. - Kuba hasn't forgotten Monica