簡體   English   中英

使用模板類復制成員函數

[英]Copy member function with template class

我的成員函數出現問題。

我的目標是創建我的集合的副本,並返回指向它的指針。

            template <class T>
            class Set
            {
            public:
                Set(int length = 0);     //Default constructor
                ~Set();              //Defualt Destructor
                int size();          //Return how many elements are in set
                bool contains(T test);   //Searches set for T
                bool add(T adding);      //Adds T to set, repeats are denied
                bool remove(T removing); //Attempts to remove T
                T** elements();      //Returns a pointer to the set
                T** copy();          //Creates a copy of the set, and returns a pointer to it
                T &operator[](int sub);  //Overload subscript

            private:
                T** set;        //Pointer to first of set
                int setSize;        //Int holding amount of Elements available
                int holding;        //Elements used
                void subError();    //Handles Subscript out of range
                void adder();       //returns a copy with +1 size
            };

這是我的構造函數和復制函數:

            template <class T>
            Set<T>::Set(int length) //Default constructor
            {
                for(int i = 0; i < length; i++)
                {
                    set[i] = new T;
                }
                setSize = length;
                holding = 0;
            }

            template <class T>
            T** Set<T>::copy()  //Creates a copy of the set, and returns a pointer to it
            {
                T** setCopy;
                for(int i = 0; i < setSize; i++)
                {
                    setCopy[i] = new T;
                    *setCopy[i] = *set[i];
                }
                return setCopy;
            }

出現錯誤,我得到一個錯誤錯誤C4700:使用了未初始化的局部變量“ setCopy”,而C4700:使用了未初始化的局部變量“ temp”,我嘗試了各種方法來進行減法運算,但這種方法無濟於事。

這里有一些問題。

首先,您需要在使用setCopy變量之前對其進行初始化。

 T** setCopy = new (T*)[setSize]

可能就是您想要的; 這表示setCopy指向setSize -to- T指針數組。 只有在那之后,您才能告訴它setCopy成員setCopy指向T的數組。 (您也需要在默認構造函數中執行相同的操作)。

但是,如果要創建集合的copy ,則應編寫一個copy構造函數和一個賦值運算符 ,而不是編寫一個copy方法,以便編寫

Set<int> set2 = set1;

並做正確的事。

setCopy實際上是未初始化的...想想在T** setCopy; 它指向哪里?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM