【问题标题】:return reference to element of dynamic array in C++?在 C++ 中返回对动态数组元素的引用?
【发布时间】:2016-04-21 18:08:31
【问题描述】:

这就是你返回对索引为 i 的动态分配数组元素的引用的方式吗??

    int& dynamic_array::operator[](unsigned int i) {
    if (i >= get_size())
        throw exception(SUBSCRIPT_RANGE_EXCEPTION);
    else
        return array[i];
}

【问题讨论】:

  • 是的,没错
  • 要使其能够用于const 对象,您需要添加const 重载。 else 也是多余的,因为 throw 在该点中止执行流程。
  • 考虑使用 std::out_of_range 而不是 std::exception

标签: c++ reference dynamic-memory-allocation


【解决方案1】:

通过尝试以优雅的方式对 cme​​ts 进行总结,您可以使用以下内容:

#include <stdexcept>
#include <string>

int& dynamic_array::operator[](size_t index)
{
    if (index >= size)
        throw std::out_of_range{"Index too large " + std::to_string(index)};
    return elements[index];
}

一个。 size_t 确保 0 或正索引

b. out_of_range 是我们在这些情况下除外的标准例外

c。异常消息信息丰富

如果我们想更进一步,您通常也需要 const 和非 const 版本。为了避免代码重复,你这样移动:

#include <stdexcept>
#include <string>
#include <utility>

const int& dynamic_array::operator[](size_t index) const
{
    if (index >= size)
        throw std::out_of_range{"Index too large " + std::to_string(index)};
    return elements[index];
}

int& dynamic_array::operator[](size_t index)
{
    return const_cast<int&>(std::as_const(*this)[index]);
}

(std:as_const() 属于 C++17 否则考虑 static_cast)

【讨论】:

    猜你喜欢
    • 2014-05-23
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    相关资源
    最近更新 更多