I am very new to C++. I am comfortable with Java and Python and I am trying to do a quickstart into C++.
I am trying to figure out how to declare/define a non-member function that takes an argument to a class object by-reference. I am unable to compile my code. I have tried to replicate the problem in the set of three files below.
I am using eclipse (Luna) as an IDE which in turn is using g++ on Ubuntu 14.04. In this set I get a cryptic compile error in the declaration of the non-member function in MyTest.h, which goes like "explicit qualification in the declaration of 'void mytest::printInt(ostream&, MyTest&)"
In my real world example I am getting a very similar error in the definition (not declaration) of the analogue of this function.
Initially I thought it has to do with me preventing the compiler from creating a default constructor and the "MyTest& m" somehow needing a default constructor (though that totally didn't make any sense to me). But declaring and defining a default constructor doesn't change the problem.
What am I doing wrong? What is the right way to define a non-member function that takes class objects as arguments by-reference)? What are some larger lessons to be had from this?
In file Mytest.h:
#ifndef MYTEST_H_
#define MYTEST_H_
#include<iostream>
namespace mytest {
using std::ostream;
class MyTest {
public:
MyTest(int a) : a(a) {}
int getA() { return a; }
private:
int a;
};
void mytest::printInt(ostream& os, mytest::MyTest& m);
} /* namespace mytest */
#endif /* MYTEST_H_ */
In file MyTest.cpp
#include "MyTest.h"
namespace mytest {
void mytest::printInt(ostream& os, MyTest& m){
os << m.getA();
}
} /* namespace mytest */
And finally a file to run them, Test.cpp:
#include "MyTest.h"
using mytest::MyTest;
using std::cout;
using std::endl;
int main(void) {
MyTest a = MyTest(1);
mytest::printInt(cout, a);
}