【问题标题】:c++ overload operator() for assigning value in a dynamic 2D arrayc ++重载运算符()用于在动态二维数组中赋值
【发布时间】:2015-02-18 21:31:07
【问题描述】:

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

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类型语句的正确构造应该是什么?

【问题讨论】:

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


    【解决方案1】:

    您不能有仅在返回类型上有所不同的重载。为了得到你想要的效果,添加一个const:

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

    并保持其他重载

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

    可以在方法声明的末尾使用const 重载方法。它的作用如下:

    1. 如果创建的对象是const test,则将调用int operator()(int row, int col) const
    2. 如果创建的对象是test(不是const),则将调用int &amp;operator(int row, int col)

    【讨论】:

    • 为什么投反对票?这是编译器给出错误的正确原因!请解释
    • 你的回答没有帮助,我没有发布这个来查找代码中的错误,我的问题是如何重载 () 运算符,以便我可以执行 t(2,2) = 5 类型的编码构造。
    【解决方案2】:

    你的第一个重载必须是形式:

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

    没有

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 2013-03-30
      • 2016-08-30
      • 1970-01-01
      相关资源
      最近更新 更多