[Solved] Operator<< Overloading for std::cout, does not work.
-
wrote on 30 Nov 2011, 17:09 last edited by
I have simple console project in Qt, where I am overloading << operator.
The next files:- Overload_operation.pro
- main.cpp
- MyClass.cpp
- MyClass.h
Contents:
Overload_operation.pro
@QT += core
QT -= guiTARGET = Overload_operation
CONFIG += console
CONFIG -= app_bundleTEMPLATE = app
SOURCES += main.cpp
MyClass.cppHEADERS +=
MyClass.h
@
main.cpp
@#include <QtCore/QCoreApplication>
#include <iostream>
#include "MyClass.h"using namespace std;
int main(int argc, char *argv[])
{
cout << "Test" << endl;
return 0;
}@
MyClass.h
@#ifndef MYCLASS_H
#define MYCLASS_H#include "iostream"
using namespace std; ///< Using std/// My simple Class
class MyClass
{
private:
int m_val; ///< value
public:
MyClass();void setVal(int val); ///< set value int val(); ///< get value /// Set the friend function friend ostream& operator<<(ostream& cout_, const MyClass& obj_);
};
/// overloading operator<<
ostream& operator<<(ostream& currCout, const MyClass& currObj)
{
currCout << currObj.m_val;
return currCout;
}#endif // MYCLASS_H@
MyClass.cpp
@#include "MyClass.h"
#include "iostream"MyClass::MyClass()
{
m_val = 0;
}void MyClass::setVal(int val)
{
m_val = val;
}int MyClass::val()
{
return m_val;
}@But I get the next errors:
@
D:\Projects_Qt\MyExamples\Overload_operation-build-desktop-Qt_4_7_4_for_Desktop_-_MinGW_4_4__Qt_SDK__Debug\debug\MyClass.o:-1: In function `ZlsRSoRK7MyClass':D:\Projects_Qt\MyExamples\Overload_operation-build-desktop-Qt_4_7_4_for_Desktop_-_MinGW_4_4__Qt_SDK__Debug..\Overload_operation\MyClass.h:24: multiple definition of `operator<<(std::ostream&, MyClass const&)'
D:\Projects_Qt\MyExamples\Overload_operation-build-desktop-Qt_4_7_4_for_Desktop_-_MinGW_4_4__Qt_SDK__Debug..\Overload_operation\MyClass.h:24: error: first defined here
:-1: error: collect2: ld returned 1 exit status
@Here is written that "multiple definition of `operator<<(std::ostream&, MyClass const&)'", but when was it?
How I can make it correct?Thanks.
——————
Best regards,
Galiego710 -
wrote on 30 Nov 2011, 18:44 last edited by
The problem is, that you implement the function in the header file, which implies, it is implemented in each include. Implement it inthe cpp file and it is fine.
-
wrote on 1 Dec 2011, 04:00 last edited by
I put it
@/// overloading operator<<
ostream& operator<<(ostream& currCout, const MyClass& currObj)
{
currCout << currObj.m_val;
return currCout;
}@
in any cpp file. It's work!
Strangely, before I did about the same, but did not work.I found a few useful links for operator<< qDebug() in Qt doc
http://doc.trolltech.com/4.6/debug.html#providing-support-for-the-qdebug-stream-operator
http://doc.trolltech.com/4.6/custom-types.htmlThank you very much!
-
wrote on 1 Dec 2011, 18:52 last edited by
It works in the header file if you have an operator definition inside a class declaration.
1/4