0

我使用代码块构建了我的程序,但对于学校,我们应该通过 linux 系统进行编译。我在下面遇到了这些错误,但我在使用 149 时遇到了问题。我不知道它在抱怨什么。也许有人可以帮助我?

In file included from matrix.cpp:9:0:
matrixClass.h: In member function âT Matrix<T>::GetData(int, int) const [with T = int]â:
matrixClass.h:149:17:   instantiated from âstd::ostream& operator<<(std::ostream&, const Matrix<int>&)â
matrix.cpp:22:13:   instantiated from here
matrixClass.h:131:16: warning: converting to non-pointer type âintâ from NULL

我的代码如下。

T GetData(int row, int column) const
{
    if (row>=0 && row<numrows() && column>=0 && column<numcols())
    {
        return pData[GetRawIndex(row, column)];
    }
    return NULL;
}

//Output matrix arrays here.
friend ostream& operator<<(ostream& os, const Matrix<T>& matrix)
{
    os << "[";
    for(int i = 0; i<matrix.numrows(); i++)
    {
        for(int j = 0; j < matrix.numcols(); j++)
            os << matrix.GetData(i,j) << " ";

        os << endl;
    }
    os << "]" <<endl;
    return os;
}
4

2 回答 2

2

There are no errors. That's just a single warning. The lines tell you:

  1. Which file included the file with the warning.
  2. Which template function the warning occurred.
  3. In which function that template function was instantiated.
  4. The line at which the instantiation occurred.
  5. The warning itself.

The warning is telling you that you're returning NULL when the return type of your function is int (T = int). Although NULL just gives you 0, the compiler is well aware that NULL is only supposed to be used with pointers and gives you a warning that you're probably doing something wrong.

于 2013-02-13T22:30:12.083 回答
2

首先,代码是正确的,尽管可能不是您真正的意思,这就是编译器警告您的原因。

在 C++ 中,NULL定义为0(整数 0),因此在您的实例化中Matrix<int>,如果用户尝试越界访问元素,您将返回 0(整数值 0)。NULL用于指示不引用有效内存的指针,编译器看到您在 return 语句中使用它...所以它想知道您是否真的打算返回指针或值 0...

这就引出了一个问题,你为什么要回来NULL?您真的是要返回 0 吗?因为如果您不这样做,编译器只会帮助您找到错误...

于 2013-02-13T22:34:18.477 回答