求助,运算符重载遇到的问题
练习运算符重载,写的一个处理字符串的类String,头文件String.h,如下:
********************************************
#ifndef STRING_H
#define STRING_H
#include <iostream>
using std::ostream;
using std::istream;
class String{
friend ostream &operator<<( ostream &, const String & );
friend istream &operator>>( istream &, String & );
public:
String( const char * = "" );
String( const String & );
~String();
const String &operator=( const String & );
const String &operator+=( const String & );
bool operator!() const;
bool operator==( String & ) const;
bool operator!=( String &right ) const{
return !( *this == right );
}
bool operator<( String & ) const;
bool operator>( String &right ) const{
return ( right < *this );
}
bool operator<=( String &right ) const{
return !( *this > right );
}
bool operator>=( String &right ) const{
return !( *this < right );
}
char &operator[]( int );
const char &operator[]( int ) const;
String operator()( int, int );
int getLength() const;
private:
int length;
char *sPtr;
void setString( const char * );
};
#endif
********************************************
其中
bool operator>( String &right ) const{
return ( right < *this );
}
编译提示:
c:\users\zhym\documents\visual studio 2010\projects\fig8.7\fig8.7\string.h(28): error C2679: 二进制“<”: 没有找到接受“const String”类型的右操作数的运算符(或没有可接受的转换)
c:\users\zhym\documents\visual studio 2010\projects\fig8.7\fig8.7\string.h(26): 可能是“bool String::operator <(String &) const”
尝试匹配参数列表“(String, const String)”时
********************************************
把right和*this换位就没有错了,即为>号重新写重载代码,不依赖<号的重载
只是想知道为什么有错,因为参考书上是这样写的
[解决办法]
形参都改成const String &
[解决办法]
楼主,你试一下友元函数吧。一般二元操作符(除+=,-+等等运算赋值操作符)用友元函数比较好。
//overloaded operator friends friend bool operator<(const String &st1,const String &st2); friend bool operator>(const String &st1,const String &st2);//overloaded operator friendsbool operator<(const String &st1,const String &st2){ return(strcmp(st1.str,st2.str)<0);}//=================================================bool operator>(const String &st1,const String &st2){ return st2<st1;}