gpt4 book ai didi

C++:容器元素的引用

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:52:08 24 4
gpt4 key购买 nike

我尝试使用返回引用const 引用operator[] 编写容器多项式。但是当我想在引用内部使用 const operator[] 时,C++ 选择了没有 constoperator[]。我应该将 const operator[] 实现为私有(private)函数并在两个地方都使用它,还是有办法让编译器使用 const 返回函数?

template <typename T>
class Polynomial {
std::vector<T> data;

void DeleteTopZeroes () {
int degree = Degree ();
while (degree && !data[degree]) {
--degree;
}
data.resize (degree + 1);
}

public:
Polynomial (T constantTerm) {
data.resize (1);
data[0] = constantTerm;
}
int Degree () const {
return data.size () - 1 ? data.size () - 1: data[0] ? 0 : -1;
}

typedef size_t size_type;
typedef const T& const_reference;

const_reference operator[] (size_type degree) const {
return degree <= Degree () ? data[degree] : 0;
}

class reference {
Polynomial<T>& _polynomial;
int _degree;

public:
reference (Polynomial<T>& polynomial, size_type degree)
: _polynomial (polynomial)
, _degree (degree)
{}
reference operator= (const T& rhs) {
if (_degree <= _polynomial.Degree ()) {
_polynomial.data[_degree] = rhs;
_polynomial.DeleteTopZeroes ();
} else if (rhs) {
_polynomial.data.resize (_degree + 1, 0);
_polynomial.data[_degree] = rhs;
}
}
operator const T&() const {
return _polynomial[_degree];
// compiler uses "reference operator[] (size_type degree)" and stucks on recursion
// but there is "const_reference operator[] (size_type degree) const"
// which seems to be more similar, isn't it
}
};

reference operator[] (size_type degree) {
return reference (*this, degree);
}
};

最佳答案

尝试 return static_cast<const Polynomial&>(_polynomial)[_degree];强制编译器选择 const 版本。

好吧,事实证明使用哪种强制转换是有争议的,所以这里有一种不需要任何强制转换的方法。

    operator const T&() const {
const Polynomial& temp = _polynomial;
return temp[_degree];
}

关于C++:容器元素的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26550679/

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