简体   繁体   中英

How to make an overload operator which works with pointers

As in the subject I need operator which will work with pointers so I do not have to call *a>*b but a>b . For example my operator << works with the pointers ok:

friend ostream& operator<< (ostream &wyjscie, Para const* ex){
    wyjscie << "(" << ex->wrt << ", " << ex->liczbaWystapien <<")"<< endl;
    return wyjscie;
}

but this one give me an error:

friend bool operator> (Para const *p1, Para const *p2){
        return p1->wrt > p2->wrt;
}

Error   1   error C2803: 'operator >' must have at least one formal parameter of class type

Unfortunately, there isn't a way to overload an operator with two pointer values. This has to do with the ambiguity of such an overloaded operator.

However, you can do this with references instead - but you'd still need to use the * operator if you want to keep pointers:

friend bool operator> (Para const &p1, Para const &p2){
    return p1.wrt > p2.wrt;
}

Your overloaded << works because it is being called on an ostream object (ostream.operator<<()).

The pointer overload of operator < does not work because a pointer is not a class so the following is meaningless: (const Para*).operator<().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM