简体   繁体   English

如何使重载运算符与指针一起使用

[英]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 . 就像在本主题中一样,我需要可以与指针一起使用的运算符,因此我不必调用*a>*b而是a>b For example my operator << works with the pointers ok: 例如,我的运算符<<与指针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<<()). 重载<<之所以起作用,是因为它是在ostream对象(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<(). 运算符<的指针重载不起作用,因为指针不是类,因此以下内容毫无意义:(const Para *)。operator <()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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