| 查看: 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 ] |
» 猜你喜欢
为什么nbs上溴 没有产物点出现呢
已经有7人回复
拟解决的关键科学问题还要不要写
已经有9人回复
最失望的一年
已经有17人回复
求推荐博导
已经有4人回复
存款400万可以在学校里躺平吗
已经有34人回复
求助一下有机合成大神
已经有4人回复
求推荐英文EI期刊
已经有5人回复
26申博
已经有3人回复
基金委咋了?2026年的指南还没有出来?
已经有10人回复
疑惑?
已经有5人回复
» 本主题相关价值贴推荐,对您同样有帮助:
C++ Cookbook 中文清晰版》(清华大学出版)【已搜索无重复】
已经有91人回复
VC++中函数返回数组指针或者带指针的结构体的编译方式是否可取?
已经有6人回复
复制构造函数问题
已经有14人回复
【分享】数据结构算法与应用 C++语言描述
已经有9人回复

【答案】应助回帖
★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★
感谢参与,应助指数 +1
cw277: 金币+20, ★★★★★最佳答案, 早点来嘛, 我都解决了才来~ 2012-09-13 14:55:54
xzhdty: 谢谢 2012-09-13 15:44:59
感谢参与,应助指数 +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













回复此楼