免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1966 | 回复: 6
打印 上一主题 下一主题

[C++] 关于const的一个问题,编译错误 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-02-20 12:23 |只看该作者 |倒序浏览
10可用积分
一个小程序,一个类的内部定义了operator==比较运算符
> cat t.cpp
struct a{
       int x;
       bool operator==(const a& ia){return x==ia.x;}
};
bool f(const a& ia, const a& ib){
     return ia==ib;
}
int main(int argc, char *argv[])
{
    return 0;
}

在solaris8(gcc2.95),devcpp4992, linux gcc 4.1.2下面编译都得到下面这样的错误:
> gcc t.cpp
t.cpp: In function `bool f(const a &, const a &':
t.cpp:6: passing `const a' as `this' argument of `bool a:perator ==(const a &' discards qualifiers

为什么说丢失了类型限定? 我分明都加了const 关键字啊!

谢谢!

最佳答案

查看完整内容

you have two choicesr just do likeAnd the first is better

论坛徽章:
0
2 [报告]
发表于 2009-02-20 12:23 |只看该作者

回复 #1 jeanlove 的帖子

you have two choices:

struct a{
        int x;
        bool operator==(const a& ia) const {return x==ia.x;}
};
bool f(const a& ia, const a& ib){
        return ia==ib;
}
int main(int argc, char *argv[])
{
        return 0;
}


or just do like

struct a{
        int x;
        bool operator==(const a& ia) {return x==ia.x;}
};
bool f(a& ia, const a& ib){
        return ia==ib;
}
int main(int argc, char *argv[])
{
        return 0;
}


And the first is better

论坛徽章:
0
3 [报告]
发表于 2009-02-20 12:35 |只看该作者
一堆笑脸,看起来乱乱的

论坛徽章:
0
4 [报告]
发表于 2009-02-20 12:46 |只看该作者
原帖由 jeanlove 于 2009-2-20 12:23 发表
一个小程序,一个类的内部定义了operator==比较运算符
> cat t.cpp
struct a{
       int x;
       bool operator==(const a& ia){return x==ia.x;}
};
bool f(const a& ia, const a& ib){
     return ...

你没定义错,而是用错了
去掉f()函数的两个const

论坛徽章:
0
5 [报告]
发表于 2009-02-20 12:52 |只看该作者
这个应该这样
struct a{
       int x;
       bool operator==(const a& ia) const {return x==ia.x;}
};
bool f(const a& ia, const a& ib) {
     return ia==ib;
}
int main(int argc, char *argv[])
{
    return 0;
}
或者这样:struct a{
       int x;
       bool operator==(const a& ia) {return x==ia.x;}
};
bool f(a& ia, const a& ib) {
     return ia==ib;
}
int main(int argc, char *argv[])
{
    return 0;
}

论坛徽章:
0
6 [报告]
发表于 2009-02-20 16:14 |只看该作者
原帖由 drowsyboy 于 2009-2-20 12:47 发表
you have two choices:

struct a{
        int x;
        bool operator==(const a& ia) const {return x==ia.x;}
};
bool f(const a& ia, const a& ib){
        return ia==ib;
}
int main(int ar ...

谢谢,问题解决,给分!

论坛徽章:
0
7 [报告]
发表于 2009-02-20 16:39 |只看该作者
来晚了,没分了
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP