【发布时间】:2023-03-24 08:38:02
【问题描述】:
我收到了一个练习来实现一个通用的 Matrix 类。 其中一项任务如下:“重载 operator(),它获取参数 (unsigned int, unsigned int) 两次,一次为 const,一次为非 const。”。
现在,经过大量搜索,我明白他们的签名应该是这样的:
T operator()(unsigned int rows, unsigned int colls) const; //cout << "A" << endl;
T & operator()(unsigned int rows, unsigned int colls); //cout << "B" << endl;
但是,无论我尝试以哪种方式调用它们,都只会调用第二个:
int main()
{
Matrix<int> mat(2, 3);
mat(1, 1) = 3;
int i= (9 + mat(1, 1)) ;
i = mat(2, 1);
cout << i << endl;
if (i == mat(1, 2)) {}
int j = Matrix<int>(2, 2)(1, 1); //calls constructor and then subscription.
}
输出将是:
B
B
B
0
B
B
【问题讨论】:
-
您的代码没有理由调用函数的 CV 限定版本,因为
Matrix的实例是const或右值。将您的Matrix变量更改为const,它将被调用。 -
试试
int x = Matrix<int>(2, 3); -
@πάντα ῥεῖ 刚刚尝试过,并没有改变任何东西。
-
@Captain Obvlious 我的理解是,重载两次的全部意义在于,一个将用于右值?如果我将变量更改为 const 确实会被调用,但是为什么不使用右值呢?或者我只是没有正确理解任务?
标签: c++ c++11 matrix operator-overloading