gpt4 book ai didi

c++ - 如何在不违反 const 限制的情况下在模板类中动态分配空间?

转载 作者:行者123 更新时间:2023-11-28 01:41:31 25 4
gpt4 key购买 nike

这是我第一次使用模板,请考虑这是一个新手问题。

我想做的是保持使用 operator[] 的便利,但将函数构造为动态数组增长,例如 vector。我一直被 const 违规错误弄得一团糟。我更喜欢使用 vector ,但每当我执行 x[ndx] = value 时,我都会遇到运行时错误。我终于放弃了,正在尝试创建自己的 vector 版本。

示例代码是:

#ifndef VECTOR_H
#define VECTOR_H

using namespace std;
template <typename T>
class Vector {
private:
long _ndx = 0;
T* _ptr; // storage for T objects
public:
Vector() { }
T& operator[](const long ndx) { _ndx = ndx; return _ptr[ndx]; }
};

#endif // VECTOR_H



# include <iostream>
# include "Vector.h"

using namespace std;

struct X {
long a;
long b;
void toString() { cout << a << " " << b << endl; }
};

class Y {
private:
long _ndx =0;
Vector<X*> word;
public:
Y() { }
X* operator[](const long ndx) const { return word[ndx]; }
};

int main(int argc, char** argv) {
Y y;
X* x = y[0];
}

错误是:

    main.cpp:20:58: error: passing 'const Vector<X*>' as 'this' argument
discards qualifiers [-fpermissive]
X* operator[](const long ndx) const { return word[ndx]; }

In file included from main.cpp:4:0: Vector.h:13:12: note: in call to 'T& Vector<T>::operator[](long int) [with T = X*]'
T& operator[](const long ndx) { _ndx = ndx; return _ptr[ndx]; }

从stackoverflow上的其他问题我理解错误。我无法让 -fpermissive 工作。实际代码更改 Vector::operator[] 来做两件事,调整 _ndx 的高水位线,当 _ndx 超过某个阈值时,增加 vector 大小,这里是 T* _ptr,将旧信息复制到新空间并删除 vector 并使用新空间。我不知道如何“优雅地”做到这一点。

最佳答案

如果我们暂时忽略设计的适当性,您可以将 ndx_ 更改为 mutable 成员并将成员函数更改为 const 成员函数以获取对该成员的 const 引用。您可以添加一个非 const 成员函数来获取一个非 const 引用,从而允许您使用数组运算符修改 vector 的内容。

using namespace std;
template <typename T>
class Vector {
private:

// |
// v
mutable long _ndx = 0;

T* _ptr; // storage for T objects
public:
Vector() { }

// The const version
// | |
// v v
T const& operator[](const long ndx) const { _ndx = ndx; return _ptr[ndx]; }

// The non-const version
T& operator[](const long ndx) { _ndx = ndx; return _ptr[ndx]; }
};

关于c++ - 如何在不违反 const 限制的情况下在模板类中动态分配空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46941448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com