24小时热门版块排行榜    

查看: 252  |  回复: 1

cw277

木虫 (正式写手)

[求助] 一个c++程序 重载的问题、、

不用友元函数,怎么去重载这个大于号?


#include
#include
using namespace std;

class String
{public:
String( ){p=NULL;}
String(char *str);
bool operator>(String &string1,String &string2);// 这里不用友元,我想用成员函数
void display( );
private:
char *p;                                       //字符型指针,用于指向字符串
};
String::String(char *str)
{p=str;}

void String::display( )                             //输出p所指向的字符串
{cout<
bool String:: operator > (String &string1,String &string2)      //定义运算符重载函数
{
         if(strcmp(string1.p,string2.p)>0)
         return true;
         else return false;
}

void main()
{
        String string1("Hello" ) ,string2("Book" ) ;
        cout<<(string1>string2)< }

[ Last edited by cw277 on 2012-9-12 at 23:09 ]
回复此楼

» 猜你喜欢

» 本主题相关价值贴推荐,对您同样有帮助:

感谢生活让我慢慢学会控制自己的情绪,学会包容与忍耐,学会不再去期待
已阅   关注TA 给TA发消息 送TA红花 TA的回帖

Daithm

新虫 (初入文坛)

【答案】应助回帖

★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★
感谢参与,应助指数 +1
cw277: 金币+20, ★★★★★最佳答案, 早点来嘛, 我都解决了才来~ 2012-09-13 14:55:54
xzhdty: 谢谢 2012-09-13 15:44:59
用成员函数的话,由于在隐性传递了this指针,所以已经有了一个参数,对 operator> 进行重载,只需要再加上另外一个参数即可。 修改后代码:
#include
#include
using namespace std;

class String
{
public:
String( ){p=NULL;}
String(char *str);
bool operator>(String& string1); // 这里不用友元,我想用成员函数
void display( );
private:
        char *p;                                       //字符型指针,用于指向字符串
};
String::String(char *str)
{p=str;}

void String::display( )                             //输出p所指向的字符串
{cout<
bool String:: operator > (String &string1)      //定义运算符重载函数
{
        if(strcmp(p,string1.p)>0)
                return true;
        else
                return false;
}

void main()
{
        String string1("Hello" ) ,string2("Book" ) ;
        cout<<(string1 > string2)< }
2楼2012-09-13 12:27:35
已阅   关注TA 给TA发消息 送TA红花 TA的回帖
相关版块跳转 我要订阅楼主 cw277 的主题更新
信息提示
请填处理意见