【问题标题】:C++ array like class element definitionC++ 数组类元素定义
【发布时间】:2023-03-19 04:04:01
【问题描述】:

我想为微控制器创建一个更小的向量类。

在法线向量类中,您可以执行以下操作:

myvector[1] = 100;

如何在课堂上完成这样的作业?

我试过了:

template<typename T>
class Vector
{
 private:
    T* content;
 public:
    T* operator[](unsigned int);
};
template <typename T>
T* Vector::operator[](unsigned int i)
{
    return &content[i];
}

但是,这会引发错误,而且这也不是一个好的解决方案。

那我该怎么办?

【问题讨论】:

    标签: c++ arrays oop operators


    【解决方案1】:

    在上面显示的情况下,您正在返回一个指向该值的指针,这可能是您遇到困难的原因。考虑改为返回引用:

    T& operator[](unsigned int);
    

    【讨论】:

    • &content[i] 不能用它,我不知道为什么。 Visual Studio 说“引用非常量的初始值必须是左值”
    • 啊,明白了。要定义引用,您不需要 & 运算符。你可以这样做: T& myref = content[i];
    • @DLCom 您只是在修改后的T&amp; operator[](unsigned int); 中添加了return content[i];。我还建议将unsigned int 替换为std::size_t
    猜你喜欢
    • 2017-10-11
    • 1970-01-01
    • 2022-06-28
    • 2010-12-20
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 2019-10-06
    • 2021-10-31
    相关资源
    最近更新 更多