TransWikia.com

Why is my friend function not working when put into a separate source code file in C++?

Stack Overflow Asked by katie1245 on February 22, 2021

I have the following header file:

TwoDimArray.h

class TwoDimArray {
    int** data;
    int rows, cols;
public:
    TwoDimArray(int, int);
    TwoDimArray(const TwoDimArray& orig);
    virtual ~TwoDimArray();
    const TwoDimArray& operator=(const TwoDimArray &op2);
    void random();
    TwoDimArray operator+(TwoDimArray &op2);
    TwoDimArray operator+(const int &in);
    TwoDimArray operator*(TwoDimArray &op2);
    int* operator[](int i);
    friend ostream& operator<<(ostream &os, TwoDimArray &twoDimArray);
};

And I define the friend function in my .cpp file as follows:

TwoDimArray.cpp snippet

ostream& TwoDimArray::operator<<(ostream &os, TwoDimArray &twoDimArray)
{
    for (int i = 0; i < twoDimArray.rows; i++)
    {
        os << "{";
        for (int j = 0; j < twoDimArray.cols; j++)
        {
            os << twoDimArray.data[i][j];
             if (j < twoDimArray.cols - 1)
            {
                os << ", ";
            }
        }
        os << "}";
        if (i < twoDimArray.rows - 1)
        {
            os << ", ";
        }
     }
   os << endl;
    return os;
}

For some reason, I get the following error message: TwoDimArray.cpp:171:10: error: 'std::ostream& TwoDimArray::operator<<(std::ostream&, TwoDimArray&)' must have exactly one argument

After some research I found varying answers with some people referring to the fact that "this" is implied as well as the fact that you can’t define friend functions within classes.

But this does not make sense to me because originally, there was only a .cpp file with the main method and the TwoDimArray class with no header file. And the friend function was defined within that class and there was no such error:

enter image description here

So it looks like it is possible to have a friend function defined within a class, but something weird happens when you put a declaration in a header file.

One Answer

Your declaration of the friend function is correct. But in your .cpp file, this definition:

ostream& TwoDimArray::operator<<(ostream &os, TwoDimArray &twoDimArray) {

is defining a member function of TwoDimArray, which is not what you declared in the .h file. (The compiler error message is telling you this).

Instead, you need to define a free function like this:

ostream& operator<<(ostream &os, TwoDimArray &twoDimArray) {

that matches the friend declaration.

Answered by cigien on February 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP