2

I am trying to serialize a custom class I have made, given a pointer to an instance of the class. This code fails to compile because it can't resolve the operator<<(out, myObj).

QDataStream& operator<<(QDataStream &out, MyObj const *&m);
QDataStream& operator>>(QDataStream &in, MyObj *&m);

void MainWindow::serialize(QDataStream &out)
{
  MyObj *myObj = new MyObj();
  operator<<(out, myObj);
}

void MainWindow::deserialize(QDataStream &in)
{
  MyObj *myObj = new myObj();
  operator>>(in, myObj);
}

QDataStream &operator<<(QDataStream &out, MyObj const *&) { return out; }

QDataStream &operator>>(QDataStream &in, MyObj *&) { return in; }

The compile error is as follows:

MainWindow.cpp:79:33: error: call of overloaded 'operator<<(QDataStream&, MyObj*&)' is ambiguous
MainWindow.cpp:79:33: note: candidates are:
../Qt5.0.1/5.0.1/gcc_64/include/QtCore/qchar.h:395:28: note: QDataStream& operator<<(QDataStream&, QChar) <near match>
../Qt5.0.1/5.0.1/gcc_64/include/QtCore/qchar.h:395:28: note:   no known conversion for argument 2 from 'MyObj*' to 'QChar'
...

Interestingly, the compiler only fails to find the first operator overload. I am able to fix this by using object references rather than references to object pointers, but I am curious why this will not compile.

Why would the compiler be unable to find the implementation of the first operator?

4

1 回答 1

1

在您调用 to 时operator<<,您正试图将 aMyObj*转换为 aMyObj const *&

乍一看,这看起来是有效的。毕竟,您正在添加const-ness。但是C++ 不允许

考虑一下你的函数的这种可能的实现,看看为什么。

QDataStream &operator<<( QDataStream &out, MyObj const *& refptr )
{
   static const MyObj const_thing;
   refptr = &const_thing;
   return out;
}

此代码将修改提供的(非常量)指针MyObj *myObj,使其现在指向一个声明为 const的对象。

如果你想要那个特定的函数签名你可以通过提供一个常量正确的指针来解决这个问题。

void serialize(QDataStream &out)
{
  MyObj *myObj = new MyObj();
  const MyObj *myConstObj = myObj; // THIS is the pointer that will be referenced
  operator<<(out, myConstObj);
}

否则,请考虑仅删除引用。

QDataStream& operator<<(QDataStream &out, MyObj const *m);
于 2013-04-18T23:02:28.260 回答