Overloading the C++ indexing subscript operator [] in a manner that allows for responses to updates

后端 未结 6 1203
我在风中等你
我在风中等你 2020-12-08 10:32

Consider the task of writing an indexable class which automatically synchronizes its state with some external data-store (e.g. a file). In order to do this the class would n

6条回答
  •  执笔经年
    2020-12-08 10:47

        #include "stdafx.h"
        #include 
    
        template
        class MyVector
        {
            T* _Elem; // a pointer to the elements
            int _Size;  // the size
        public:
            // constructor
            MyVector(int _size):_Size(_size), _Elem(new T[_size])
            {
                // Initialize the elemets
                for( int i=0; i< _size; ++i )
                    _Elem[i] = 0.0;
            }
            // destructor to cleanup the mess
            ~MyVector(){ delete []_Elem; }
        public:
            // the size of MyVector
            int Size() const
            {
                return _Size;
            }
            // overload subscript operator
            T& operator[]( int i )
            {
                return _Elem[i];
            }
        };
    
    
        int _tmain(int argc, _TCHAR* argv[])
        {
            MyVector vec(10);
            vec[0] =10;
            vec[1] =20;
            vec[2] =30;
            vec[3] =40;
            vec[4] =50;
    
            std::cout<<"Print vector Element "<
                                                            
提交回复
热议问题