【问题标题】:Implemtation of += operator oveloaded for the Class Vector. C++为类向量重载的 += 运算符的实现。 C++
【发布时间】:2022-07-21 19:43:55
【问题描述】:

我需要在 C++ 中实现 += 运算符的重载。我有一个 Vector 类,我的 += 实现需要从我的 Vector 后面添加一个整数。

例如:如果我的向量 V1 包含 {1, 2, 3} 并且我写 V1 += 4,它需要给我 {1, 2, 3, 4}。

我与 + 运算符的重载具有几乎相同的功能,它接收一个 Vector 和一个 int 并将给定的整数添加到数组的后面。

我的班级的字段 '''

class Vector
{
    unsigned int _size;
    int * _list;

'''

这是我对 += 操作员的非工作解决方案 '''

Vector& operator+=(const int val)
{
    Vector temp;
    temp._list = new int[_size + 1];
    temp._size = this->_size + 1;

    for (unsigned int i = 0; i < temp._size; i++)
    {
        if (i < temp._size - 1)
        {
            temp._list[i] = this->_list[i];
        }
        else if (i == temp._size - 1)
        {
            temp._list[i] = val;
        }
    }
    return temp;
}

'''

+ 操作员几乎相同的工作解决方案 '''

friend Vector operator+(Vector lhs, const int val)
    {
        Vector temp;
        temp._list = new int[lhs._size + 1];
        temp._size = lhs._size + 1;

        for (unsigned int i = 0; i < temp._size; i++)
        {
            if (i < temp._size - 1)
            {
                temp._list[i] = lhs._list[i];
            }
            else if (i == temp._size - 1)
            {
                temp._list[i] = val;
            }
        }
        return temp;
    }

'''

我不明白关键区别在哪里,但我猜它在 & 或朋友概念中的某个地方,因为我真的不明白它们在这种情况下是如何工作的。

还有一件事我不能改变我的方法的描述。 (只是实现)

【问题讨论】:

  • “这是我的非工作解决方案...” 非工作是什么意思?你有任何错误。或者别的什么。
  • 您不能返回对局部变量的引用。
  • 您的 operator+= 由于返回对本地的引用而损坏。
  • 我还建议您花一些时间阅读this canonical implementation reference 以了解重载运算符。从中您应该了解到所有赋值运算符都应该返回对*this 的引用(并修改this,而不是创建新对象)。
  • @pptaszni 通常,二元运算符应该从复合赋值运算符实现,而不是相反。所以+应该使用+=来实现。

标签: c++ class oop operator-overloading


【解决方案1】:

+= 运算符中,您应该将新值设置为要自行添加的向量。

另请注意,返回对非静态局部变量 temp 的引用是个坏主意。

试试这个:

Vector& operator+=(const int val)
{
    Vector temp;
    temp._list = new int[_size + 1];
    temp._size = this->_size + 1;

    for (unsigned int i = 0; i < temp._size; i++)
    {
        if (i < temp._size - 1)
        {
            temp._list[i] = this->_list[i];
        }
        else if (i == temp._size - 1)
        {
            temp._list[i] = val;
        }
    }
    // move the data in temp to this object
    this->_size = temp._size;
    delete[] this->_list;
    this->_list = temp._list;
    // assign new array to temp for being destructed
    temp._list = new int[1];
    temp._size = 1;
    // return a reference to this object
    return *this;
}

【讨论】:

    猜你喜欢
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 2017-09-04
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    相关资源
    最近更新 更多