【发布时间】:2013-10-31 03:23:31
【问题描述】:
我的成员函数有问题。
我的目标是创建我的集合的副本,并返回一个指向它的指针。
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” 我已经尝试了各种去影响的方法等,但我无济于事。
【问题讨论】:
-
隐藏该方法的前提是一个糟糕的想法,
T** setCopy = new T*[setSize]可能会让您更接近。您还应该考虑使用setCopy[i] = new T(*(set[i]));作为循环中的唯一语句,尽管正如我所说,这种方法甚至没有被公开。如果您的目标是创建集合的副本,则创建Set<T>的副本,而不仅仅是底层指针数组的快照。此外,此类具有动态成员,并且没有复制构造函数或赋值运算符重载,因此您实际上是在玩等待发生的事故。
标签: c++