为什么要写两()运算符

Buf*_*lls 6 c++

为什么要两次?这2行,为什么这样做?一个够吗?

inline T& operator() (int row, int col) { return this->m_data[row*NC + col]; }

const inline T& operator() (int row, int col) const { return this->m_data[row*NC + col]; }
Run Code Online (Sandbox Code Playgroud)

谢谢

 *
 * 2-DIMENSIONAL ARRAY
 *
 * Simulated by 1-dimension array.
 ******************************************************************************/

#ifndef __2D_ARRAY_H__
#define __2D_ARRAY_H__
#include <stdint.h>
#include <stdlib.h>

namespace alg {
    /**
     * 2D Array definition
     */
    template <typename T=char>
        class Array2D {
            private:
                uint32_t NR;        // num of rows
                uint32_t NC;        // num of columns
                T * m_data;         // the place where the array resides.

            public:
                /**
                 * construct an array of size [nrow,col]
                 */
                Array2D(uint32_t nrow, uint32_t ncol) {
                    NR = nrow;
                    NC = ncol;  
                    m_data = new T[nrow*ncol];
                }

                /**
                 * destructor
                 */ 
                ~Array2D() {
                    delete [] m_data;
                }

            private:
                Array2D(const Array2D&);    
                Array2D& operator=(const Array2D&); 

            public:

                /**
                 * return number of rows of this array
                 */
                inline const uint32_t row() const { return NR; }
                /**
                 * return number of columns of this array
                 */
                inline const uint32_t col() const { return NC; }

                /**
                 * return the value by the given (row, col);
                 */
                inline T& operator() (int row, int col) { return this->m_data[row*NC + col]; }
                const inline T& operator() (int row, int col) const { return this->m_data[row*NC + col]; }

                inline T* operator[] (int row) { return &(m_data[row * NC]); }
                inline const T* operator[] (int row) const { return &(m_data[row * NC]); }

                /**
                 * clear the array by a given value
                 */
                void clear(const T & value) {
                    for(uint32_t i=0; i<NR*NC;i++){
                        m_data[i] = value;
                    }
                }
        };
}

#endif //
Run Code Online (Sandbox Code Playgroud)

Ada*_*dam 10

一个是const,另一个不是.

不同之处在于,当您有一个const引用时,Array2D您只能调用标记的成员函数const.在这种情况下,这意味着第二个版本,它必须返回const对它所拥有的元素的引用.

const但是,如果您有非引用,那么第二个版本意味着您无法使用operator()对您的更改Array2D.

如果你看一下标准库容器std::vector,就会发现它们会做同样的事情.你可以得到一个iterator来自begin()和const_iterator来自begin() const.