Overloading of operators

on Sunday, November 11, 2012
So today I tried to overload the << and >> operators (in a header file)
  QDataStream &operator<<(QDataStream &out, PlayListModel& model) { model.write(out); return out; } 

but I got multiple definition errors:
D:\Qt\PlayGen-build-desktop-Qt_4_8_1_for_Desktop_-_MinGW__Qt_SDK__Debug\..\PlayGen\\..\Mewsic\playlistmodel.h:32: multiple definition of `operator<<(QDataStream&, PlayListModel&)'

I did include guard statements in my header file. Yet it didn't seem to be working here. The header file was being included multiple times. What the heck was going on?! I did a search and finally found the problem:
No, this is a misconception on how include guards work. They will prevent multiple inclusion in the samefile, but not in multiple files.
This is the reason you should only place declarations in headers, but not definitions.
http://qt-project.org/forums/viewthread/20973 
Bingo! Being new to C++, I've been facing problems similar to these and sometimes to takes a long time to figure it out. But it's well worth it. C++ is so powerful. But I still find it very complicated. All those header files, all those operator overloading and whatnot. I feel that it's very easy to do something wrong and not realise it.

Although I still love Java the most, I'm starting to like C++... Hmm...

0 comments:

Post a Comment