错误:表达式不能用作函数-operator()

时间:2018-10-05 07:59:44

标签: c++ operator-overloading dynamic-arrays

我正在为充当TwoD数组的单个指针构建包装器类。 我有一个重载的operator()用于从数组中返回一个值。
我希望能够使用operator()访问 arr(r,c)

形式的数组值
#include <iostream>
#include <cstring>

using namespace std;

template <class T>
class TwoDArray
{
    private:
        T * arr;
        int rows, columns, size;
        int getIndex(int r, int c)
        {
            int index = (r*columns) + c;
            return index;
        }
    public:
        /*Constructor*/
        TwoDArray(int r = 1, int c = 1) : rows(r), columns(c)
        {
            if(r > 0 && c > 0)
            {
                size = rows*columns;
                arr = new T [size];
                memset(arr, 0, sizeof(int)*size);
            }

            else
            {
                arr = NULL;
            }
        }

        void setAtIndex(int r, int c, T value)
        {
            int index = getIndex(r, c);
            arr[index] = value;
        }

        //lvalue - has the effect obj(r,c);
        T& operator()(unsigned int r, unsigned int c)
        {
            if(r >= rows || c >= columns)
            {
                cerr<<"Unable to locate memory\n";
                exit(0);
            }
            return arr[getIndex(r,c)];
        }

        //rvalue - has the effect obj(r,c);
        const T& operator()(unsigned int r, unsigned int c) const
        {
            if(r >= rows || c >= columns)
            {
                cerr<<"Unable to locate memory\n";
                exit(0);
            }
            return arr[getIndex(r,c)];
        }

        void displayTwoD() const
        {
            for (int i = 0; i < rows; ++i)
            {
                for (int j = 0; j < columns; ++j)
                {
                    cout<<this->arr(i,j);
                }
                cout<<"\n";
            }
        }

        /*Destructor*/
        ~TwoDArray()
        {
            if(arr != NULL)
                delete arr;
            arr = NULL;
        }
};

int main()
{
    TwoDArray <int> tda(5,5);

    for (int i = 0; i < 5; ++i)
    {
        for (int j = 0; j < 5; ++j)
        {
            tda.setAtIndex(i,j, (i+1)*2);
        }
    }

    tda.displayTwoD();
    return 0;
}

我得到了错误:

G:\DS>g++ checkError.cpp
checkError.cpp: In instantiation of 'void TwoDArray<T>::displayTwoD() const [with T = int]':
checkError.cpp:95:18:   required from here
checkError.cpp:68:10: error: expression cannot be used as a function
      cout<<this->arr(i,j);

当我使用

cout<<arr(i,j);

代码中的任何位置。我想知道为什么会这样以及如何解决。

1 个答案:

答案 0 :(得分:1)

编辑:现在,我知道您想做什么。您要从成员函数中调用operator()。您可以通过取消引用“ this”来实现:

(*this)(i,j)

旧答案,但没有任何意义:

TwoDArray :: arr是一个指针,您需要取消对其的引用:(* arr)(i,j)