免费注册 查看新帖 |

Chinaunix

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

[C++] 一个类中两个“一样”的运算符重载函数 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-01-18 22:14 |只看该作者 |倒序浏览
在c++ FAQs中看到的一段代码
为什么一般都只调用返回引用的重载函数,另一个在什么时候调用?

#include <stdexcept>
using namespace std;

class Matrix {
public:
  double& operator() (unsigned row, unsigned col)
    throw(out_of_range);
  double  operator() (unsigned row, unsigned col) const
    throw(out_of_range);
private:
  enum { rows_ = 100, cols_ = 100 };
  double data_[rows_ * cols_];
};

inline double& Matrix::operator() (unsigned row, unsigned col)
throw(out_of_range)
{
  if (row >= rows_ || col >= cols_)
    throw out_of_range("Matrix::operator()");
  return data_[cols_*row + col];
}

inline double Matrix::operator() (unsigned row, unsigned col) const
throw(out_of_range)
{
  if (row >= rows_ || col >= cols_)
    throw out_of_range("Matrix::operator()");
  return data_[cols_*row + col];
}

int main()
{
  Matrix m;
  m(5,8) = 106.15;                                   
  cout << m(5,8);                                    
}




[ 本帖最后由 sww12081234 于 2008-1-18 22:42 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2008-01-18 23:05 |只看该作者
重载函数的Signature与返回类型无关,只与参数个数、类型和是否const成员有关。
你的类中一个重载操作符是const成员,另一个是非const成员。对于非const成员函数,只能由非const 对象调用;const对象只能调用const成员函数。由于m是非const对象,其优先选择非const版本重载函数。
PS:LZ很强,06注册,一帖

论坛徽章:
0
3 [报告]
发表于 2008-01-19 00:12 |只看该作者
2007年我去了火星 a joke
唉,都是06年的,差距就是这么大啊
谢谢了哦
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP