How to make an overload operator which works with pointers

让人想犯罪 __ 提交于 2019-12-24 06:45:14

问题


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

回答1:


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;
}



回答2:


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<().



来源:https://stackoverflow.com/questions/16291060/how-to-make-an-overload-operator-which-works-with-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!