c++ - 调用了错误的 operator() 重载

标签 c++ debugging gcc matrix operator-overloading

我正在编写一个矩阵类并且重载了函数调用运算符两次。矩阵的核心是一个二维 double 组。我正在使用从 Windows 控制台调用的 MinGW GCC 编译器。

第一个重载旨在从数组中返回一个 double 值(用于查看元素)。 第二个重载旨在返回对数组中某个位置的引用(用于更改该位置中的数据。

double operator()(int row, int col) const ; //allows view of element

double &operator()(int row, int col); //allows assignment of element

我正在编写一个测试例程,发现永远不会调用“查看”重载。出于某种原因,当使用以下 printf() 语句时,编译器“默认”调用返回引用的重载。

fprintf(outp, "%6.2f\t", testMatD(i,j));

我知道我在不使用 vector 和使用 C I/O 函数测试的情况下编写自己的矩阵类是在侮辱上帝。来世我会受到彻底的惩罚,没必要在这里做。

最终我想知道这里发生了什么以及如何解决它。我更愿意使用看起来更简洁的运算符重载而不是成员函数。

有什么想法吗?

矩阵类:省略无关代码。


    class Matrix

    {
    public:
 double  getElement(int row, int col)const; //returns the element at row,col

 //operator overloads
 double operator()(int row, int col) const ; //allows view of element
 double &operator()(int row, int col); //allows assignment of element

    private:
 //data members
 double  **array;   //pointer to data array

    };

    double Matrix::getElement(int row, int col)const{
  //transform indices into true coordinates (from sorted coordinates
  //only row needs to be transformed (user can only sort by row)
  row = sortedArray[row];

  result = array[usrZeroRow+row][usrZeroCol+col];
  return result;
    }

    //operator overloads
    double Matrix::operator()(int row, int col) const {
     //this overload is used when viewing an element
     return getElement(row,col);
    }

    double &Matrix::operator()(int row, int col){
     //this overload is used when placing an element
  return array[row+usrZeroRow][col+usrZeroCol];
    }

测试程序:省略无关代码。

int main(void){

 FILE *outp;

 outp = fopen("test_output.txt", "w+");

    Matrix testMatD(5,7); //construct 5x7 matrix

    //some initializations omitted
    fprintf(outp, "%6.2f\t", testMatD(i,j));   //calls the wrong overload
}

最佳答案

const 成员函数(“查看”函数)只有在对象是 const 时才会被调用:

const Matrix testMatD(5,7);

testMatD(1, 2); // will call the const member function

关于c++ - 调用了错误的 operator() 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2611680/

相关文章:

c++ - 两个字符串的交换元素C++

c++ - 如何判断表达式是在编译时还是运行时求值?

c++ - 将函数作为参数传递给模板函数问题

c++ - OpenCV 和 Xcode

c - 远程调试的调试技术

c++ - 识别自动生成的成员函数

c - 相同类型,全部定义,类型冲突

java - 我的代码结果不好

c - 为什么我按 's' 和 'u' 都得不到正确答案?

c - Linux中C语言中Printf()在 "while(1)"循环之前不执行