没有与这些操作数匹配的"[]"运算符

x363635334 2013-04-19 05:59:33

class String
{
public:
char *m_s;
char& operator[](int i);
friend bool operator==(const String& s1,const String &s2);//没有私有成员,friend多余?
};

char& String::operator[](int i)
{
return m_s[i];
}
bool operator==(const String& s1,const String &s2)
{
for(int i=0;s1[i];i++)//error:没有与这些操作数匹配的"[]"运算符
{
if(s1.m_s[i]!=s2.m_s[i])
return FALSE;
}
return TRUE;
}

有这两个小问题
...全文
1328 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
x363635334 2013-04-19
  • 打赏
  • 举报
回复
[quote=引用 4 楼 derekrose 的回复:] 这个就需要函数重载了quote]
还剩这个问题:
"==" 可能是bool operator==(const String &,const String &)
也可能是内置C++ operator==(char *, char *)”
当调用形如(String, CHAR [260])

貌似调用形如(String, CHAR [260])时类经过opertor char*转换 与c语言指针地址判等的那种用法产生了二义性
如何避免,还是想不出
derekrose 2013-04-19
  • 打赏
  • 举报
回复
引用 5 楼 x363635334 的回复:
Quote: 引用 4 楼 derekrose 的回复: C/C++ code?12for(int i=0;s1[i];i++)//OKfor(int i=0;s1[i]=3;i++)//error 如此测试结果是否说明s1[]只要出现在条件里总是调用只读版的,那个可写的版本何时才会被编译器调用?
看参数表,那个对象就是只读的,所以调用的成员函数也是只读的。
Athenacle_ 2013-04-19
  • 打赏
  • 举报
回复
引用 5 楼 x363635334 的回复:
Quote: 引用 4 楼 derekrose 的回复: C/C++ code?12for(int i=0;s1[i];i++)//OKfor(int i=0;s1[i]=3;i++)//error 如此测试结果是否说明s1[]只要出现在条件里总是调用只读版的,那个可写的版本何时才会被编译器调用?
当你的bool operator==(const String& s1,const String &s2)变成 bool operator==(String& s1,String &s2)的时候
x363635334 2013-04-19
  • 打赏
  • 举报
回复
[quote=引用 4 楼 derekrose 的回复:]

for(int i=0;s1[i];i++)//OK
for(int i=0;s1[i]=3;i++)//error
如此测试结果是否说明s1[]只要出现在条件里总是调用只读版的,那个可写的版本何时才会被编译器调用?
derekrose 2013-04-19
  • 打赏
  • 举报
回复
引用 3 楼 x363635334 的回复:
引用 2 楼 hello_world000 的回复:增加一个成员函数: char operator[](int i)const; 解决了,什么原理啊 还剩这个问题: "==" 可能是bool operator==(const String &,const String &) 也可能是内置C++ operator==(char *, char ……
const无法调用非const函数 这个就需要函数重载了。
x363635334 2013-04-19
  • 打赏
  • 举报
回复
引用 2 楼 hello_world000 的回复:
增加一个成员函数: char operator[](int i)const;
解决了,什么原理啊 还剩这个问题: "==" 可能是bool operator==(const String &,const String &) 也可能是内置C++ operator==(char *, char *)” 当调用形如(String, CHAR [260])
hello_world000 2013-04-19
  • 打赏
  • 举报
回复
增加一个成员函数: char operator[](int i)const;
x363635334 2013-04-19
  • 打赏
  • 举报
回复
可能是“内置 C++ operator[(char *, int)” 或 “char &String::operator [](int)” 1> 尝试匹配参数列表“(const String, int)”时 “operator ==”: 2 个重载有相似的转换 可能是“bool operator ==(const String &,const String &)”内置 C++ operator==(char *, char *)” 1> 尝试匹配参数列表“(String, CHAR [260])”时 仅仅是因为我的类有char*转换,我是模仿CString的,怎么遇到这个事

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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