Search code examples
c++overloadingoperator-keyword

C++ << operator overloading without friend function


Exactly as the topic says. Is there a possibility to do that? I was able to achieve this in overloading '+' operator, however, I could not do this with '<<' operator.

This is an example of code that works for me with friend function:

class Punkt2D
{
    int x,y;

    public:
        Punkt2D(int wartoscX, int wartoscY) : x(wartoscX), y(wartoscY) {}
        friend ostream& operator<<(ostream& out, Punkt2D& punkt);
};

ostream& operator<<(ostream& out, Punkt2D& punkt)
{
    out << "(" << punkt.x << ", " << punkt.y << ")" << endl; 
    return out;
}

int main()
{
    Punkt2D p1(10,15);

    cout << p1 << endl;
    return 0;
}

I tried this code on '+' without befriending the function. Is it also possible for other operators? Maybe it is a silly question, however I am quite new to C++ and could not find any resource on the topic :(

class Vector
{
    public:

    double dx, dy;
    Vector() {dx=0; dy=0;}
    Vector(double x, double y) 
    {
        cout << "Podaj x " << endl;
        cin >>x;
        cout << "Podaj y " << endl;
        cin >> y;
        dx = x; dy = y;

    }
    Vector operator+ (Vector v);
};


Vector Vector::operator+ (Vector v)
{
    Vector tmpVector;
    tmpVector.dx = dx +v.dx;
    tmpVector.dy = dy+ v.dy;
    return tmpVector;
}

int main()
{
    double d,e;

    Vector a(d,e);
    Vector b(d,e);
    Vector c;
    c = a +b;
    cout<<endl << c.dy << " " << c.dx;
    return 0;
}

Solution

  • As long as the function only calls public member functions of the class (or accesses public data members, if any) it does not need to be a friend.

    Your Vector example is only accessing public members, hence it works.

    Your Punkt2D is accessing private members, so the operator needs to be a friend.