I can't figure out why the following code doesn't compile. The syntax is the same as my other operator overloads. Is there a restriction that the << overload must be friended? If so, why? Thanks for any help.
This doesn't work -
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
class Test
{
public:
explicit Test(int var):
m_Var(var)
{ }
std::ostream& operator<< (std::ostream& stream)
{
return stream << m_Var;
}
private:
int m_Var;
};
int _tmain(int argc, _TCHAR* argv[])
{
Test temp(5);
std::cout << temp;
return 0;
}
This does work -
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
class Test
{
public:
explicit Test(int var):
m_Var(var)
{ }
friend std::ostream& operator<< (std::ostream& stream, Test& temp);
private:
int m_Var;
};
std::ostream& operator<< (std::ostream& stream, Test& temp)
{
return stream << temp.m_Var;
};
int _tmain(int argc, _TCHAR* argv[])
{
Test temp(5);
std::cout << temp;
return 0;
}