使用模板类复制成员函数
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;
}
有错误我收到 ar 错误错误 C4700:使用了未初始化的局部变量"setCopy"和 C4700:使用未初始化的局部变量"temp"我已经尝试了各种去修饰方法等,但我无
这里有几个问题。
首先,您需要在使用setCopy
变量之前对其进行初始化。
T** setCopy = new (T*)[setSize]
可能是你想要的; 这表示setCopy
指向一组setSize
指向T
的指针。只有在那之后,你才能告诉它,setCopy
的任何成员都指向一个T
数组。(您也需要在默认构造函数中执行相同的操作)。
但是,如果你想要的是创建集合的副本,那么你应该编写一个复制构造函数和一个赋值运算符,而不是编写一个copy
方法,以便你可以编写
Set<int> set2 = set1;
并让它做正确的事情。
setCopy 实际上是未初始化的...想一想T** setCopy;
后它指向哪里?
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 访问类成员而不复制此变量或互斥变量
- std::ofstream 作为类成员删除复制构造函数?
- 正在复制具有未初始化成员的结构
- 直接初始化不可复制、不可移动的成员,而不使用聚合初始化
- 具有 STL 向量类型成员的类的复制内存
- 是否可以将不可复制的成员用作使对象不可复制的替代方法?
- 将C++浮点数组成员直接封送到 C#,而无需复制
- 在临时将成员带出时省略复制/移动
- 复制赋值函数如何访问另一个对象的私有成员(Stroustroup 原则和实践书)?
- C++ 阻止复制成员数据
- C++列表:复制成员列表中的本地列表
- 使用模板类复制成员函数
- 即使复制构造函数由于 RVO 在C++中未被调用,如何复制成员变量的值
- 具有不可复制成员的类的聚合初始化
- 请参阅 TC++PL 第 3 版的第 10.4.6.3 节"复制成员"
- 初始化不可复制成员
- 关于包含不可复制成员引用的类的复制构造函数的建议
- 错误到底是什么,对于错误地调用可移动和不可复制成员的复制构造函数有什么解决方法