[英]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.