c++ 重载 operator() 用于在动态二维数组中赋值

标签 c++ c++11 operator-overloading dynamic-memory-allocation

我正在尝试重载 () 运算符以将值赋值到动态分配的二维数组中,这是我的代码 --

class test {
    private:
        int** data ; int row, col ;

    public:
        test(int row = 2, int col = 2)  {
            this->row = row ; this->col = col ;
            this->data = new int*[this->row] ;
            for(int i = 0 ; i < this->row ; i++)
                this->data[i] = new int[this->col] ;
        }

        ~test() {
            for(int i = 0 ; i < this->row ; i++)
                delete [] this->data[i] ;
            delete [] this->data ;
        }

        const int operator() (int row, int col) { // read operation
            return this->data[row][col] ;
        }

        int& operator() (int row, int col) { // write operation
            return this->data[row][col] ;
        }

        // for printing
        friend ostream& operator<< (ostream &os, const test &t);
};

在 operator() 写操作中,我试图通过引用返回值,以便我可以像这样赋值 --

test t(4,4) ;
t(2,2) = 5 ;

但它不编译,说我不能做这种重载,那么可以用来实现 t(2,2) = 5 类型的正确构造应该是什么的声明?

最佳答案

您的第一个重载必须采用以下形式:

int operator() (int row, int col) const

不是

const int operator() (int row, int col)

而且不是读操作,当你类型的对象被创建为const时使用,会使用这个重载,如果不是const,其他将使用重载,用于读取和写入。

关于c++ 重载 operator() 用于在动态二维数组中赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27574639/

相关文章:

c++ - 将 std::vector 分配给方法内的指针

asp.net-mvc-3 - 即使运算符重载也无法转换为字符串

c++ - 为什么 std::array::size constexpr 具有简单类型(int、double、...)而不是 std::vector (GCC)?

c++ - 在 std::string 上执行正则表达式搜索和替换

c++ - 重载 operator<< 和 operator+ 导致错误

python - 如何根据参数类型重载 __init__ 方法?

c++ - clang 和 gcc 中的 Constexpr 复合赋值运算符

c++ - 用 C++ 编写状态机

c++ - 显示QImage的方式

c++ - 在 C++ 中复制函数参数