Returning multidimensional array from function

后端 未结 7 954
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 03:51

How do I return a multidimensional array stored in a private field of my class?

class Myclass {
private:
   int myarray[5][5];
public:
   int **         


        
7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 04:07

    I managed to make this function work in C++0x using automatic type deduction. However, I can't make it work without that. Native C arrays are not supported very well in C++ - their syntax is exceedingly hideous. You should use a wrapper class.

    template class TwoDimensionalArray {
        T data[firstdim][seconddim];
    public:
        T*& operator[](int index) {
            return data[index];
        }
        const T*& operator[](int index) const {
            return data[index];
        }
    };
    class Myclass {
    public:
        typedef TwoDimensionalArray arraytype;
    private:
        arraytype myarray;
    public:
        arraytype& get_array() {
            return myarray;
        }
    };
    
    int main(int argc, char **argv) {
        Myclass m;
        Myclass::arraytype& var = m.get_array();
        int& someint = var[0][0];
    }
    

    This code compiles just fine. You can get pre-written wrapper class inside Boost (boost::array) that supports the whole shebang.

提交回复
热议问题