重载模板运算符

Overloading template operators

本文关键字:运算符 重载      更新时间:2023-10-16

我正试图在我的模板Vector类上重载+=运算器。

template<unsigned int dimensions, typename TValue>
class Vector
{
private:
    std::array<TValue, dimensions> m_values;
public:
    Vector(){
        for (int i = 0; i < dimensions; i++){
            m_values[i] = TValue();
        }
    };
    Vector(std::array<TValue, dimensions> elements){
        for (int i = 0; i < dimensions; i++){
            m_values[i] = elements[i];
        }
    };
    
    inline void set(VectorDimensions dimension, TValue value){
        m_values[dimension] = value;
    };
    
    inline TValue get(VectorDimensions dimension) const{
        return m_values[dimension];
    };
    inline unsigned int getSize() const{
        return dimensions;
    };
    const std::array<TValue, dimensions> getValues() const{
        return m_values;
    };
    friend ostream& operator<<(ostream& os, const Vector<dimensions, TValue>& vt) {
        array<TValue, dimensions> values = vt.getValues();
        os << '[';
        for (unsigned int i = 0; i < vt.getSize(); i++){
            os << values[i] << values[i+1] ? ", " : "";
        }
        os << ']';
        return os;
    };
    friend Vector<dimensions, TValue>& operator+=(const Vector<dimensions, TValue>& vt) {
        array<TValue, dimensions> values = vt.getValues();
        for (unsigned int i = 0; i < vt.getSize(); i++){
            m_values[i] += values[i];
        }
        return *this;
    };
};

在为+=运算器添加过载后,我得到了以下许多错误:

错误C2805:二进制"operator+="的参数太少

错误C4430:缺少类型说明符-假定为int。注意:C++不支持默认的int

错误C2334:"{"之前的意外令牌;正在跳过明显的函数体。

错误C2238:";"前面有意外的令牌

语法错误:缺少";"在'<'之前

错误C2143:语法错误:缺少";"在"++"之前

错误C2143:语法错误:在";"之前缺少")"

错误C2059:语法错误:"return"

错误C2059:语法错误:"for"

错误C2059:语法错误:")"

解释一下为什么或如何导致这些错误,无论我做错了什么,都可能是有用的。感谢

我能够通过删除+=运算符定义之前的friend关键字来停止错误。根据本页http://en.cppreference.com/w/cpp/language/operators

class X {
 public:
  X& operator+=(const X& rhs) // compound assignment (does not need to be a member,
  {                           // but often is, to modify the private members)
    /* addition of rhs to *this takes place here */
    return *this; // return the result by reference
  }
  // friends defined inside class body are inline and are hidden from non-ADL lookup
  friend X operator+(X lhs,       // passing first arg by value helps optimize chained a+b+c
                    const X& rhs) // alternatively, both parameters may be const references.
  {
     return lhs += rhs; // reuse compound assignment and return the result by value
  }
};

这就是+和+=运算器过载的方式。