문제

Hello I'm in the process of learning about operator overloading and friend functions.

I've declared the operator<< function as a friend of my class in a .h file but I still cant access the private member variables from the function definition in a .cpp file

My code is as follows:

Test.h

class Test
{
private:
    int size;
public:
    friend ostream& operator<< (ostream &out, Test& test);
};

Test.cpp

#include "Test.h"
#include <iostream>

using namespace std;

ostream& operator<< (ostream& out, Test& test)
{
    out << test.size; //member size is inaccessible!
}

Apparently size is inaccessible although I've already made the operator<< function a friend of my class. I've Googled a bit and haven't found anything so can anyone help me out? Thanks.

Note: If I move the class definition to the .cpp file everyone works so I assume my problem has something to do with multiple files.

도움이 되었습니까?

해결책

In c++ the scope of the declaration go from top to bottom. So if you include first Test.h and after that <iostream> the friend declaration has does not know about the type std::ostream.

The solution:

Test.h:

#include <iostream>
class Test
{
private:
    int size;
public:
    friend std::ostream& operator<< (std::ostream &out,const Test& test);
};

Test.cpp:

#include "Test.h"

std::ostream& operator<< (std::ostream& out,const Test& test)
{
    out << test.size;
    return (*out);
}

Note that the #include <iostream> has been moved from Test.cpp to Test.h and the argument of the global operator << takes const Test& test. The const makes the operator work for rvalues.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top