C++ 运算符重载和设置值
我创建了一个容器类,并将new关键字与指针结合使用,以了解它是如何工作的,以及如何使用它C++ 运算符重载和设置值,c++,operator-overloading,C++,Operator Overloading,我创建了一个容器类,并将new关键字与指针结合使用,以了解它是如何工作的,以及如何使用它 template<typename T> class Container { private: T value; public: Container(T value) { this->value = value; } Container() { } virtual ~Container() { } T ge
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;
}
模板
类容器{
私人:
T值;
公众:
容器(T值){
这个->值=值;
}
容器(){
}
虚拟容器(){
}
T getValue(){
返回值;
}
无效设置值(T值){
这个->值=值;
}
无效运算符[](T值){
这个->值=值;
}
};
int main(){
std::载体arr(10);
对于(int i=0;i<10;i++){
容器*a=新容器;
a->设定值(i);
//a[我];
arr[i]=a;
std::cout getValue()setValue(i)
并且使用a[i]
它只打印一个随机数。为什么
T& operator*() { return value; }
T& operator->() { return value; }
也可以添加赋值运算符(将替换setValue):
T& operator*() { return value; }
T& operator->() { return value; }
也可以添加赋值运算符(将替换setValue):
一致
Container<int> *a = new Container<int>;
您只需使用存储在a
中的地址和偏移量i*sizeof(容器)
所以正确的用法应该是
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;
}
std::向量arr(10);
对于(int i=0;i<10;i++){
容器*a=新容器;
(*a)[i];
arr[i]=a;
std::cout getValue()行中
Container<int> *a = new Container<int>;
您只需使用存储在a
中的地址和偏移量i*sizeof(容器)
所以正确的用法应该是
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;
}
std::向量arr(10);
对于(int i=0;i<10;i++){
容器*a=新容器;
(*a)[i];
arr[i]=a;
std::cout getValue()我建议您阅读重载运算符。您的错误。下标运算符将索引作为其参数,并且必须返回赋值将更新的引用。我建议您阅读重载运算符。您的错误。下标运算符将索引作为其参数,并且必须返回赋值将更新的引用赋值将更新。我将其更改为void operator=(T const&value){this->value=value;},并且它比Container更有效&作为返回值,仍然正确吗?他没有访问operator[]
从类容器中
根本不存在问题there@Sly_TheKing他在问题中注释了它-然后问为什么垃圾,如果使用它…我说如果他使用了注释行,他仍然没有访问操作符[]
来自类容器。查看我的答案以准确了解我的答案mean@Sly_TheKing看到那个已经猜到的人(在这个注释出现时)向上投票…我把它改为void操作符=(T const&value){this->value=value;}而且它比Container更有效&作为返回值,仍然正确吗?他没有访问操作符[]
从类容器中
根本不存在问题there@Sly_TheKing他在问题中注释了它-然后问为什么垃圾,如果使用它…我说如果他使用了注释行,他仍然没有访问操作符[]
来自类容器。查看我的答案以准确了解我的答案mean@Sly_TheKing看到那个已经猜到的人(在发表这篇评论的时候)投了赞成票。。。