1
我想为微控制器创建一个更小的向量类。C++数组像类元素定义
在正常向量类,你可以这样做:
myvector[1] = 100;
怎么可能实现一类这样的作业吗?
我尝试这样做:
template<typename T>
class Vector
{
private:
T* content;
public:
T* operator[](unsigned int);
};
template <typename T>
T* Vector::operator[](unsigned int i)
{
return &content[i];
}
但是,抛出的错误,也不会是一个很好的解决方案。
那我该怎么办?
&内容[我]不能用它,我不知道为什么。 Visual Studio说“引用非const的初始值必须是一个左值” – DLCom
啊,明白了。要定义参考,您不需要&运算符。 你可以这样做: T&myref = content [i]; – DLCom
@DLCom你只是'在你修改过的T&operator [](unsigned int);'中返回content [i];'我也建议用['std :: size_t'](http://en.cppreference.com/w/cpp/types/size_t)替换'unsigned int'。 – vsoftco