samedi 26 mars 2022

Is it correct overloaded operator declaration? [duplicate]

I am learing for exam and need to know if this declaration of operator+ is correct, it works as I wish but I am not sure how it works.

#include <iostream>
using namespace std;

class name {
private:
    string word;

public:
    name(const string& a1) :word(a1) {}

    friend name& operator+(const string& la, name& ra);
    friend ostream& operator<<(ostream& out, const name& r);
};

ostream& operator<<(ostream& out, const name& r) {
    return out<<r.word;
}

name& operator+(const string& la, name& ra) {
    ra.word = la + ra.word;
    return ra;
}

int main() {
    name obj("overflow");
    obj = "stack" + obj;
    cout << obj << endl;
}

I was just editing my operator+ until it compiles and somehow this one comiples.

Aucun commentaire:

Enregistrer un commentaire