简体   繁体   中英

Custom Vector class, return vector like an array in c++

I'm trying to create a custom vector class and overloading all operators. consider the following code:

  template <class T>
  class vector{

     private:
     T * arrayOfObj;
     // other class members

    public:

     Vector(){
      arrayOfObj = new T[100];
     }
     vector(int size); 
     // other functions for vector class, overloaded [], =, etc.
    }

in another class, I need to return the vector but with a pointer like when we return an array:

   #include "B.h"
   class c {

     vector<B> vect;

     public:
     B * getArray(){
       return vect;
     }

First, is it possible to retrun a vector like an array? Also, if I wanted to access the dynamic array encapsulated inside the vector class without using a public function to return the array, how should be my approach?

First, is it possible to retrun a vector like an array?

Sure, that's what std::vector::data() does. It's as simple as doing return arrayOfObj; in whatever method or operator overload.

Also, if I wanted to access the dynamic array encapsulated inside the vector class without using a public function to return the array, how should be my approach?

Not possible. Either you allow access to your internal storage via a public function or you don't allow that, your choice. In c::getArray() you could also copy all elements of vect into a new array - this way noone will alter vect from the outside and you don't have to provide access to internal storage of vector class.

There is also friend mechanism that allows one function or class to access private members of another class, but it's usually worse than public access .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM