Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this << overload compile

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;
 }
like image 869
Steve Avatar asked May 19 '26 12:05

Steve


1 Answers

It's not a restriction that any operator must be "friended". The problem is that, if you declare an operator as an instance method, the first argument is always forced to be the type of the class itself. In this case, you need the first parameter of the operator (left hand side) to be of type std::ostream& therefore, you can't use an instance method to overload it and will have to use a global function.

By the way, it's not at all required that operators declared as separate functions to be declared as friend functions too. They can happily work without being a friend of the class as long as they only access public members of their arguments.

like image 157
mmx Avatar answered May 21 '26 04:05

mmx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!