使用模板类复制成员函数

Copy member function with template class

本文关键字:复制 成员 函数      更新时间:2023-10-16

>我在使用成员函数时遇到问题。

我的目标是创建我的集合的副本,并返回指向它的指针。

            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;
            }

有错误我收到 ar 错误错误 C4700:使用了未初始化的局部变量"setCopy"和 C4700:使用未初始化的局部变量"temp"我已经尝试了各种去修饰方法等,但我无

处可去。

这里有几个问题。

首先,您需要在使用setCopy变量之前对其进行初始化。

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

可能是你想要的; 这表示setCopy指向一组setSize指向T的指针。只有在那之后,你才能告诉它,setCopy的任何成员都指向一个T数组。(您也需要在默认构造函数中执行相同的操作)。

但是,如果你想要的是创建集合的副本,那么你应该编写一个复制构造函数和一个赋值运算符,而不是编写一个copy方法,以便你可以编写

Set<int> set2 = set1;

并让它做正确的事情。

setCopy 实际上是未初始化的...想一想T** setCopy;后它指向哪里?