运算符 = 回合侧一个按值秒按引用

operator= bout side one by value second by refrence?

本文关键字:一个 引用 运算符      更新时间:2023-10-16

Q 是如何做到这种运算符=它将在以下方面工作:

int t = v[3];//her i return by Value

v[3] = 8 ;//她我需要通过引用返回(指向 V[3] add'的指针)

Will V 是一个向量类(在我的例子中是模板类)

 template <class T> 
 T& Vector<T>::operator[](const int Index) const
 {
  if(Index > -1 && Index < this->Size)
  {
    return &this->Array[Index];
  }
else
   {
        cerr <<"VECTOR_INVALID_INDEX"<<endl;
        return NULL;
   }
};

此示例中有几个错误。 this已经是一个指针。做&this几乎可以肯定不是你在这里想做的。您遇到的另一个问题是,您返回的引用T但在这种情况下this是常量。 this->Array[Index]是无法绑定到T&const T。添加一个常量并改为返回const T&。第三,this->Size没有调用方法Size,你忘记了括号。第四个问题是对 NULL 的引用绑定。您将不得不决定另一种方法。指示无法完成操作的常用方法是引发异常。std::vector::at 从标头 stdexcept 抛出 std::out_of_range。

template <class T>
const T& Vector<T>::operator[](const int Index) const
//^^^ add const here
{
    if (Index > -1 && Index < this->Size())
    //                  Add parentheses ^^ 
    {
        return this->Array[Index];
        //     ^ No need for &
    }
    else
    {
        throw std::out_of_range("VECTOR_INVALID_INDEX");
    }
};

您可能还希望添加一个非 const 版本,因为这对于示例v[3] = 8;将失败。使用相同的主体定义此方法:

T& Vector<T>::operator[](const int Index);