【问题标题】:C++ Indexing an array of ints using a shortC ++使用short索引整数数组
【发布时间】:2023-03-04 17:14:01
【问题描述】:

好吧,伙计们,我在 15 分钟前问了一个问题并关闭了它,因为当我在 main() 中尝试一个简单的测试时,它成功了。但是,它在实际代码中不起作用:

背景,我有一个无符号整数数组,我无法通过无符号短索引器访问它们。如果我在堆栈上声明一个数组,它可以工作,但它不适用于我的数组数据成员。

这里是数组声明:

typedef unsigned int uint;

class OB{
public:
    OB();
    void x(unsigned short side_pos);

private:
    uint best_p[2]; 
};

这是我得到编译器错误的代码:

void OB::x(unsigned short side_pos){
    unsigned int best_price = best_p[side_pos];
}

如果我这样做:

void OB::x(unsigned short side_pos){
    unsigned short something_else = 1;
    unsigned int best_price = best_p[something_else];
}

我也得到编译器错误,即:

OB.cpp: In member function ‘void OB::x(short unsigned int)’:
OB.cpp:62:56: error: invalid types ‘unsigned int[short unsigned int]’ for array subscript
     unsigned int best_price = best_p[side_pos];

【问题讨论】:

  • 你确定这是 only best_p 并且没有局部变量吗?
  • @chris 把它作为答案(你说得对,在我的一个编译器错误中,我确实有一个多重声明,但对于另一个我没有,并把“this->my_array[]”修复了它)。
  • 更好:使用不同的名称。阴影有时很有用,但通常只会导致编译错误。
  • @user997112 我在上一篇文章中已经说过你总是尝试编译你自己的代码片段。有那么难吗?!!!你的代码 sn-p 编译成功。

标签: c++ arrays indexing int short


【解决方案1】:

根据直觉和注释提示,您有一个局部变量 best_p(从外观上看是 unsigned int),它隐藏了您的班级成员。因此,best_p[side_pos] 将使用局部变量,而不是数据成员。

如果你想让编译器捕捉阴影,-Wshadow 选项应该可以做到。最好的办法是重命名某些东西。对数据成员名称进行约定(m_<name> 是一种常见约定)也有助于防止意外隐藏和考虑将某些内容重命名为什么。

【讨论】:

    【解决方案2】:

    它在我的电脑上编译。似乎获得该错误的方法是使用变量而不是数组。检查属性的名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      相关资源
      最近更新 更多