[英]Assigning to Typename Array Class C++
I'm trying to write an array wrapper class for a project.我正在尝试为一个项目编写一个数组包装器 class。 Everything is working ok, except I'm not able to assign values ( array[i] = value; ) that already exist in the array, I keep getting "expression must be a modifyable lvalue".一切正常,除了我无法分配数组中已经存在的值( array[i] = value; ),我不断收到“表达式必须是可修改的左值”。 I tried to overload the assignment operator but had no luck.我试图重载赋值运算符,但没有成功。
#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]; }
};
Any help would be much appreciated!任何帮助将非常感激!
You apply the []
operator.您应用[]
运算符。
Then you attempt to assign to what that returns.然后您尝试分配给返回的内容。
What it returns is a copy of T
, because of T operator[](int index) { return data[index]; }
它返回的是T
的副本,因为T operator[](int index) { return data[index]; }
T operator[](int index) { return data[index]; }
. T operator[](int index) { return data[index]; }
。
You'd have to return a reference.你必须返回一个参考。
As kindly pointed out by HolyBlack Cat, it would be almost needed to also have正如 HolyBlack Cat 善意指出的那样,几乎还需要
a second
operator[]
that'sconst
and returnsconst T &
第二个operator[]
是const
并返回const T &
because因为
It just allows you to call
[]
on const objects/references to read the values.它只允许您在 const 对象/引用上调用[]
来读取值。
Eg if you define a const version of what you are implementing.例如,如果您定义了您正在实施的内容的 const 版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.