【发布时间】:2021-08-28 07:55:19
【问题描述】:
std::ostream& operator<<(std::ostream& ostr, const Vector& right_hand_side)
{
for (int i = 0; i < right_hand_side.size; ++i)
{
// Printing array integers
ostr << right_hand_side.array[i] << " ";
}
ostr << std::endl;
return ostr;
}
我有一个自定义矢量类。它运行良好,但仅适用于整数值。我想扩展它的功能并添加 char 值。我需要实现这样的结果,即可以为 int 和 char 创建向量。此重载运算符仅显示 int 值。如何让它支持 char 值? 这是vector类的头文件
#pragma once
#包括
class Vector {
public:
Vector(); // Default constructor
Vector(const Vector& rhs); // copy constructor
Vector(int elements, int value = 0);
Vector(const std::initializer_list<int>& list);
~Vector(); // destructor
void PushBack(int value); // Add an element to the end of the vector.
void PushBackChar(int value); // Add an element to the end of the
矢量。
void PopBack(); // Deletes the element at the end of the vector.
bool Empty() const; // Tests if the vector container is empty.
int Size() const; // Returns the number of elements in the vector.
int Capacity() const; // Returns the number of elements that the vector could contain without allocating more storage.
bool operator==(const Vector& right_hand_side) const;
bool operator!=(const Vector& right_hand_side) const;
friend std::ostream& operator <<(std::ostream& ostr, const Vector& rhs);
Vector& operator=(const Vector& rhs);
int& operator[](int index);
int& At(int index); // Returns a reference to the element at a specified location in the vector.
int& Front(); // Returns a reference to the first element in a vector.
int& Back(); // Returns a reference to the last element of the vector.
void Insert(int index, int value); // Inserts an element or many elements into the vector at a specified position.
void Erase(int index); // Removes an element or a range of elements in a vector from specified positions.
void Clear(); // Erases the elements of the vector.
private:
int size;
int capacity;
int* array;
char* char_array;
};
【问题讨论】:
-
你需要实现vector类来支持chars。 vector 目前是如何实现的?顺便说一句,你为什么这样做而不使用 std::vector?
-
任务是我需要从头开始创建我的矢量类,而不使用标准矢量类的实用程序和 C++ 的模板功能
-
如果不分享Vector类的任何信息,我们将无法帮助您
-
哈哈。你是对的)我们被要求重新发明自行车。也许它很好,也许不是,我不知道,但它仍然是一种体验