confusing error
-
I'm trying to use a function that takes a QByteArray* and returns QInt32. The IDE has an error message: "'this' argument to member function 'byteArrayToUint32' has type 'const MainWindow', but function is not marked const".
Marking the function (or anything else for that matter) as const doesn't change anything, so I'm wondering what the actual issue might be.
Here are my declarations in MainWindow.h:
QByteArray *ba; qint32 byteArrayToUint32(QByteArray &bytes);
and where I call the function in MainWindow.cpp:
QByteArray fbytes; ba->resize(query.size()); fbytes = byteArrayToUint32(ba); // <- error is marked here
and the function in MainWindow.cpp:
quint32 byteArrayToUint32(QByteArray &bytes) { auto count = bytes.size(); if (count == 0 || count > 4) { return 0; } quint32 number = 0U; for (int i = 0; i < count; ++i) { auto b = static_cast<quint32>(bytes[count - 1 - i]); number += static_cast<quint32>(b << (8 * i)); } return number; }
-
@MScottM said in confusing error:
QByteArray fbytes;
ba->resize(query.size());
fbytes = byteArrayToUint32(ba); // <- error is marked herefbytes is a QByteArray, byteArrayToUint32() returns an quint32
ba is a pointer, byteArrayToUint32 takes a reference
ba gets resized but never initialized, you access the data of this container (when it would compile) inside byteArrayToUint32() so you will get garbage. -
@Christian-Ehrlicher this is where my lack of formal training is shining through... but, thanks to your reply, I have figured out I am going about what I am trying to do in the wrong way. I'm going to have to redo this bit of code somehow.
Marking this solved - even though it's more like...a lesson learned (maybe).
-
-
@MScottM said in confusing error:
The IDE has an error message: "'this' argument to member function 'byteArrayToUint32' has type 'const MainWindow', but function is not marked const".
Here is another lesson to learn: The error tells us that
byteArrayToUint32
is a member function ofMainWindow
. And the error also tells us that you are calling this function from within another function that is marked asconst
. For member functions everything after the argument list applies to the implicitthis
pointer in member functions. And even though you are not writing it explicitly you are actually callingthis->byteArrayToUint32(ba)
. If thethis
pointer isconst
it can only call member functions that are also marked asconst
. So, the easy solution is to declare your function const:quint32 byteArrayToUint32(QByteArray &bytes) const;
However, your conversion function actually does not need the
this
pointer in any way. You can either have it as a free-standing function (declared outside of your class). This might pollute your global namespace unnecessarily. Another approach is to mark itstatic
. The latter would be the general approach I'd prefer.