[英]Operator overloading and setting values
I created a Container class and used the new keyword in combination with pointers to learn how it works and how I can use it. 我创建了一个Container类,并将new关键字与指针结合使用以了解其工作方式以及如何使用它。
template<typename T>
class Container {
private:
T value;
public:
Container(T value) {
this->value = value;
}
Container() {
}
virtual ~Container() {
}
T getValue() {
return value;
}
void setValue(T value) {
this->value = value;
}
void operator[](T value) {
this->value = value;
}
};
int main() {
std::vector<Container<int>*> arr(10);
for (int i = 0; i < 10; i++) {
Container<int> *a = new Container<int>;
a->setValue(i);
// a[i];
arr[i] = a;
std::cout << arr[i]->getValue() << std::endl;
delete a;
}
return 0;
}
The []
operator has the same code as setValue()
, but it only prints the numbers from 0 to 9 if I use a->setValue(i)
and with using a[i]
it prints just a random number. []
运算符具有与setValue()
相同的代码,但是如果我使用a->setValue(i)
,则仅打印从0到9的数字,而使用a[i]
则仅打印随机数。 Why? 为什么?
T& operator[](size_t index)
{
return value;
}
Actually, as you do not have anything you could apply an index to (the only valid index in your case would be 0 – or from another point of view, with above implementation, any index would return the same value, so &a[0] == &a[1] would apply - which might be syntactically correct, but violates the semantics of an index operator...), dereferencing operators would be more appropriate: 实际上,由于您什么都没有,因此可以将索引应用于(在您的情况下,唯一有效的索引将是0 –或从另一个角度来看,通过上述实现,任何索引都将返回相同的值,因此&a [0] ==&a [1]将适用-语法上可能正确,但是违反了索引运算符的语义...),因此取消引用运算符会更合适:
T& operator*() { return value; }
T& operator->() { return value; }
Possibly, you could add an assignment operator, too (would replace setValue): 可能的话,您也可以添加一个赋值运算符(将替换setValue):
Container& operator=(T const& value) { this->value = value; return *this; }
In line 排队
Container<int> *a = new Container<int>;
you initialize a
as pointer, so with this line 您将
a
初始化为指针,因此此行
a[i];
you just access some memory with address stored in a
and offset i * sizeof(container<int>)
您只需要访问一些内存,地址存储在
a
并偏移i * sizeof(container<int>)
So the correct usage would be 所以正确的用法是
std::vector<Container<int>*> arr(10);
for (int i = 0; i < 10; i++) {
Container<int> *a = new Container<int>;
(*a)[i];
arr[i] = a;
std::cout << arr[i]->getValue() << std::endl;
delete a;
}
With (*a)[i];
用
(*a)[i];
you access operator[]
you wrote in your class 您访问您在课堂上写的
operator[]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.