Cal*_*Cal 0 c++ debugging gcc operator-overloading matrix
我正在写一个矩阵类,并重载了函数调用操作符两次.矩阵的核心是2D双阵列.我正在使用从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
Run Code Online (Sandbox Code Playgroud)
我正在编写测试例程,并发现"查看"超载永远不会被调用.由于某种原因,当使用以下printf()语句时,编译器"默认"调用返回引用的重载.
fprintf(outp, "%6.2f\t", testMatD(i,j));
Run Code Online (Sandbox Code Playgroud)
我明白,我通过编写自己的矩阵类而不使用向量和使用CI/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];
}
Run Code Online (Sandbox Code Playgroud)
测试程序:省略了不相关的代码.
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
}
Run Code Online (Sandbox Code Playgroud)
只有当对象是const时,才会调用const成员函数("查看"函数):
const Matrix testMatD(5,7);
testMatD(1, 2); // will call the const member function
Run Code Online (Sandbox Code Playgroud)