欢乐颂2里的歌曲:关于C++问题---运算符加载

来源:百度文库 编辑:中科新闻网 时间:2024/04/28 16:24:14
同样对()对加载,一个是double& operator()(int x,int y)
double operator()(int x,int y) const
程序调用时
程序怎么判断执行谁?

#include <iostream.h>
class Matrix
{
public:Matrix(int r,int c)
{row=r;col=c;
elem=new double[row*col];
}
double& operator()(int x,int y)
{return elem[col*x+y-1];
}
double operator()(int x,int y) const
{return elem[col*x+y-1];
}
~Matrix(){ delete[] elem;}
private:
double *elem;
int row,col;
};
void main()
{Matrix m(5,8);
for(int i=0;i<5;i++)
m(i,1)=i+5;
for(i=0;i<5;i++)
cout<<m(i,1)<<",";
cout<<endl;
}

如果是const对象,比如const Matrix m(5,8) 那么会加载const版本的,否则会加载普通版本的