gpt4 book ai didi

c++ - 错误 : expression cannot be used as function - operator()

转载 作者:行者123 更新时间:2023-11-28 04:31:53 26 4
gpt4 key购买 nike

我正在为充当二维数组的单个指针构建一个包装器类。我有一个重载的 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);

代码中的任何地方。我想知道为什么会发生这种情况以及如何解决。

最佳答案

编辑:现在我明白你想做什么了。你想从成员函数中调用 operator() 。您可以通过取消引用“this”来做到这一点:

(*this)(i,j)

旧答案,但没有意义:

TwoDArray::arr 是一个指针,你需要取消引用它:(*arr)(i,j)

关于c++ - 错误 : expression cannot be used as function - operator(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52660946/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com