我们需要重载运算符以从模板类的流中读取。模板类 Set 有一个字段 - 另一个模板类 Point 的元素数组:
class Set
{
public:
Set()
{
_ptr = nullptr;
_capacity = 0;
_size = 0;
}
Set(int capacity)
{
_ptr = new classType[capacity];
_capacity = capacity;
_size = 0;
}
template<class classType>
friend ostream& operator << (ostream& os, const Set<classType>& set);
template <class classType>
friend istream& operator >> (istream &stream, Set<classType>& set);
}
class Point
{
public:
Point()
{
_x = 0;
_y = 0;
_z = 0;
}
Point(T x, T y, T z)
{
_x = x;
_y = y;
_z = z;
}
template<typename T>
friend ostream& operator << (ostream& os, const Point<T>& p);
template<typename T>
friend istream& operator >> (istream &stream, Point<T>& p);
}
实现本身:
template <class classType>
istream &operator >> (istream &stream, Set<classType>& set)
{
cout << "Enter capacity: ";
stream >> set._capacity;
cout << "Enter size: ";
stream >> set._size;
cout << "Enter elements: ";
for (int i = 0; i < set._size; ++i)
stream >> set._ptr[i];
return stream;
}
template <typename T>
istream &operator >> (istream &stream, Point<T>& p)
{
stream >> p._x >> p._y >> p._z;
return stream;
}
读取容量 b 大小并开始从 _ptr (_ptr[0]) 读取第一个元素后从 gtests 崩溃
测试截图:
告诉我该怎么做?
至少,您已经有一个
Set
正在阅读的 . 使用分配的内存(恐怕为零 - 如果您在没有参数的情况下创建它)。读取时,您只需覆盖字段
_capacity
和_size
,从而已经违反了对象的内部状态 - 它认为它已经为_capacity
元素和写入的_size
元素分配了内存。但是你已经破坏了对象的一致性。然后你也开始将数据写入内存。您确定这
_ptr
表明分配了足够的内存吗?尤其是在他们简单地宣布电话之前Set<Type> set;
?情况清楚吗?