illusionist illusionist - 1 month ago 21
C++ Question

Operator Overload (<<)

I am trying to print out value from my custom datatype. I know the standard "cout << example" wont work. How would I overload the operator in this instance?

class gLoc
{
public:
int row;
int col;
};

int main ( int argc, char*argv[] )
{

//DELCARING Grid Location Storage
gLoc gridStart = gLoc{ 0 , 0 };
gLoc gridPos = gLoc{ 0 , 0 };
gLoc gridFin = gLoc{ 0 , 0 };

//Finding start of grid path
for(int x = 0; x < grid.size(); x++)
{
for(int y = 0; y < grid[x].size(); y++) //TEST printing the 2D vector
{
if(grid[x][y] == 'o')
{
gridStart = gLoc{ x , y };
}
if(grid[x][y] == 'x')
{
gridFin = gLoc( x , y);
}
}
}

return 0;
}

Answer

This is not how to initialize non-aggregate objects. As long as you specified a private access specifier for member data then your class is a non-aggregate and thus you can't write:

gLoc gridStart = {0, 0};
  • Aggregate class mustn't declare any member function or data private or protected scoped.

You either make row and col public, or overload the constructor to take two integers. But then you don't use aggregate initialization for your objects.

To overload the insertion operator "<<":

class gLoc
{
    public:
        gLoc(int, int);
        friend ostream& operator << (ostream&, const gLoc&);
    private:
        int row;
        int col;
};

gLoc::gLoc(int n, int m) : 
    row(n), col(m)
{}

ostream& operator << (ostream& out, const gLoc& rhs)
{
    out << "row: " << rhs.row << endl;
    out << "col: " << rhs.col << endl;
    return out;
}

In your application logic you should now initialize objects like this:

    gLoc gridStart(0, 0);
    gLoc gridPos  (0, 0);
    gLoc gridFin  (0, 0);