【发布时间】:2011-02-06 09:19:36
【问题描述】:
我正在编写一个矩阵类,并且两次重载了函数调用运算符。矩阵的核心是一个二维双数组。我正在使用从 Windows 控制台调用的 MinGW GCC 编译器。
第一个重载意味着从数组中返回一个双精度值(用于查看元素)。 第二个重载旨在返回对数组中某个位置的引用(用于更改该位置中的数据。
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));
我知道我编写自己的矩阵类而不使用向量和使用 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
}
【问题讨论】:
-
如果这是 C++,应该像这样编程。使用
std::vector,不是手动内存管理。使用fstream而不是fopen/fclose(提示:缺少后者)。另外,有一个get函数很奇怪,将它用于一个重载,然后对第二个重载不做任何事情(如果我没看错的话,改变行为。)
标签: c++ debugging gcc matrix operator-overloading