【问题标题】:How to overload operator "<<" to output integer values in one case and char values in another case?如何重载运算符“<<”以在一种情况下输出整数值,在另一种情况下输出字符值?
【发布时间】: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类的任何信息,我们将无法帮助您
  • 哈哈。你是对的)我们被要求重新发明自行车。也许它很好,也许不是,我不知道,但它仍然是一种体验

标签: c++ class oop vector


【解决方案1】:

如果Vector 只存储ints,那么你只有ints 可以输出。我认为您的讲师要求您拥有一个包含ints 的Vector_int 类和一个包含chars 的Vector_char 类,并且实现基本相同。

除此之外:我建议检查您现有的实现,并将作为索引或大小的int 的所有使用更改为std::size_t,这样当您复制char 的实现时,您可以进行替换-全部在您的文本编辑器中。

我希望这个练习的学习成果是“这就是模板存在的原因”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2017-08-09
    • 1970-01-01
    • 1970-01-01
    • 2011-04-20
    相关资源
    最近更新 更多