(C++)各位大侠帮忙看看这个双目运算符的重载有什么问题

hmjia 2009-04-14 11:37:14
#include <iostream>
#include <string>
using namespace std;
class String
{public:
String( ){p=NULL;}
String(char *str);
friend bool operator>(String &string1,String &string2);
void display();
private:
char *p;
};
String::String(char *str)
{p=str;}

void String::display()
{
cout<<p;
}

bool operator>(String &string1,String &string2)
{
if(strcmp(string1.p,string2.p)>0)
return true;
else
return false;
}
void main()
{
String str1("Hello "),str2("world!");
str1.display();
str2.display();
cout<<(str1>str2)<<endl;
}



用VC++6.0编译报错:error C2248: 'p' : cannot access private member declared in class 'String' ,see declaration of 'p'。
error C2593: 'operator >' is ambiguous。
...全文
149 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
LemIST 2009-04-14
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 hmjia 的回复:]
试了一下,把运算符重载函数作为类成员是可以通过的,谢谢哈。还想问一下,为什么把它作为友元函数就不行呢,是不是和编译器有关??
[/Quote]
可能是的,在vs2008里再次验证了~~
hmjia 2009-04-14
  • 打赏
  • 举报
回复
试了一下,把运算符重载函数作为类成员是可以通过的,谢谢哈。还想问一下,为什么把它作为友元函数就不行呢,是不是和编译器有关??
LemIST 2009-04-14
  • 打赏
  • 举报
回复
没装Vc6, VS2008里测试通过.
ryuk33 2009-04-14
  • 打赏
  • 举报
回复

bool operator>(String &string1,String &string2)
{
if(strcmp(string1.p,string2.p)>0)
return true;
else
return false;
}

放到,类里面去,变成:

class String
{
……
bool operator>(String &string2) const
{
if(strcmp(this->p,string2.p)>0)
return true;
else
return false;
}
……
};

65,211

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧