繁体   English   中英

分配给 Typename 数组 Class C++

[英]Assigning to Typename Array Class C++

我正在尝试为一个项目编写一个数组包装器 class。 一切正常,除了我无法分配数组中已经存在的值( array[i] = value; ),我不断收到“表达式必须是可修改的左值”。 我试图重载赋值运算符,但没有成功。


#include "stdafx.h"

#include <vector>

template <typename T>
inline bool operator==(const T left, const T right)
{
    return &left == &right;
}

template <typename T>
class TArray {

    std::vector<T> data;

public:

    TArray() { }

    void Reserve(unsigned int space)
    {
        if (space == 0)
        {
            return;
        }

        data.reserve(space);
    }

    /**
    * Adds a value
    */
    void Add(T value)
    {
        data.push_back(value);
    }

    /**
    * Adds the value if it does not already exist
    */
    void AddUnique(T value)
    {
        if (Contains(value))
        {
            return;
        }

        Add(value);
    }

    /**
    * Removes the first value in the array matching the value
    */
    void Remove(T value)
    {
        std::vector<T>::iterator itr = std::find(data.begin(), data.end(), value);
        if (itr != data.end())
        {
            data.erase(itr);
        }
    }

    /**
    * Removes all matching the type
    */
    void RemoveAllMatching(T value)
    {
        for (int i = data.size(); i >= 0; i--)
        {
            if (data[i] == value)
            {
                data.erase(i);
            }
        }
    }

    /**
    * Removes value at index
    */
    void RemoveAtIndex(int index)
    {
        if (index > data.size() - 1)
        {
            return;
        }

        data.erase(index);
    }

    /**
    * Returns true if the array contains the object
    */
    bool Contains(T value)
    {
        for (T v : data)
        {
            if (v == value)
            {
                return true;
            }
        }

        return false;
    }

    /**
    * Returns the number of the same value
    */
    int ContainsQuantity(T value)
    {
        int quantity = 0;

        for (T v : data)
        {
            if (v == value)
            {
                ++quantity;
            }
        }

        return quantity;
    }

    void Clear() { data.clear(); }

    typename std::vector<T>::const_iterator begin() const { return data.begin(); }

    typename std::vector<T>::const_iterator end() const { return data.end(); }

    int Size() { return data.size(); }

    T operator[](int index) { return data[index]; }
};

任何帮助将非常感激!

您应用[]运算符。
然后您尝试分配给返回的内容。

它返回的是T的副本,因为T operator[](int index) { return data[index]; } T operator[](int index) { return data[index]; }

你必须返回一个参考。

正如 HolyBlack Cat 善意指出的那样,几乎还需要

第二个operator[]const并返回const T &

因为

它只允许您在 const 对象/引用上调用[]来读取值。

例如,如果您定义了您正在实施的内容的 const 版本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM