Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/144.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为模板矩阵实现多个订阅运算符(运算符())_C++_C++11_Matrix_Operator Overloading - Fatal编程技术网

C++ 为模板矩阵实现多个订阅运算符(运算符())

C++ 为模板矩阵实现多个订阅运算符(运算符()),c++,c++11,matrix,operator-overloading,C++,C++11,Matrix,Operator Overloading,我收到了一个实现泛型矩阵类的练习。 其中一项任务如下:“重载运算符(),它两次获取参数se(unsigned int,unsigned int),一次作为常量,一次作为非常量。” 现在,经过多次搜索,我明白了他们的签名应该是这样的: T operator()(unsigned int rows, unsigned int colls) const; //cout << "A" << endl; T & operator()(unsigned int

我收到了一个实现泛型矩阵类的练习。 其中一项任务如下:“重载运算符(),它两次获取参数se(unsigned int,unsigned int),一次作为常量,一次作为非常量。”

现在,经过多次搜索,我明白了他们的签名应该是这样的:

    T operator()(unsigned int rows, unsigned int colls) const; //cout << "A" << endl;
    T & operator()(unsigned int rows, unsigned int colls); //cout << "B" << endl;

对于要求
operator()
的讲师来说,这很好。宇宙是有希望的

这与其说是右值/左值的东西,不如说是常量/非常量的东西。 方法定义末尾的
const
声明(编译器将执行一个合理的级别检查,以确定它不会更改对象的状态)调用方法不会更改对象的状态。如果您希望能够对常量对象调用方法,那么这是绝对必要的

如果将以下函数添加到测试代码中:

void consttest(Matrix<int> &mat, const Matrix<int> &cmat)
{
    mat(1,1) =4;
    cmat(1,1) =4;
}
你会看到好的左/右价值的东西在起作用。遗憾的是,您无法看到调用const操作符(),因为它无法编译。以它自己的方式进行了相当好的测试,该方法很好地防止了错误,但更有用的功能测试是:

void consttest(Matrix<int> &mat, const Matrix<int> &cmat)
{
    std::cout << mat(1,2) << std::endl;
    std::cout << cmat(1,2) << std::endl;
}
void consttest(矩阵和矩阵,常数矩阵和cmat)
{

std::难道你的代码没有理由调用函数的CV限定版本,因为
矩阵的实例是
常量或右值。将
矩阵
变量更改为
常量
,它将被调用。尝试类似
int x=Matrix(2,3);
@πάντα的方法ῥεῖ 只是尝试了一下,没有改变任何东西。@Captain Obvlious我所理解的是,两次重载的全部意义是一个变量将用于右值?如果我将变量更改为const,它确实会被调用,但为什么不用于右值?或者我只是没有正确理解任务?谢谢。接受这个答案是因为c几年过去了:)
void consttest(Matrix<int> &mat, const Matrix<int> &cmat)
{
    mat(1,1) =4;
    cmat(1,1) =4;
}
consttest(mat, mat);
void consttest(Matrix<int> &mat, const Matrix<int> &cmat)
{
    std::cout << mat(1,2) << std::endl;
    std::cout << cmat(1,2) << std::endl;
}