简体   繁体   English

在这种情况下魔术数字还可以吗?

[英]Are Magic Numbers Okay In This Instance?

In this question regarding magic numbers in arrays, paxdiablo says that any number other than -1, 0 and 1 are magic numbers. 这个数组中关于幻数的问题,paxdiablo说,任何数量比-1,0和1等都是幻数。 I know that this is only a guideline but I was wondering if when specifying dimensions of a multi dimensional array if I needed to define constants for which dimension was x, y and z. 我知道这只是一个准则,但我想知道在指定多维数组的尺寸时是否需要定义尺寸分别为x,y和z的常量。 For example, is this okay: 例如,这样可以吗:

typedef boost::multi_array<TileID, 3> TileArray3D;

TileArray3D::size_type GoRPG::MapData::GetWidth() {
    return mData.shape()[0]; 
}

or is this preferred: 或者这是首选:

TileArray3D::size_type GoRPG::MapData::GetWidth() {
    return mData.shape()[x_dimension]; 
}

Thanks in advance, ell. 预先感谢,ell。

Edit: The reason the lengths are stored in an array is because I am using Boost::multi_array and that is how they are stored. 编辑:长度存储在数组中的原因是因为我正在使用Boost :: multi_array,这就是它们的存储方式。 Apologies for the broken code! 对代码破损表示歉意! I can fix that later - at the moment I just would like to know about the magic numbers, although it is still useful, thank you! 我稍后可以解决-目前,我仅想了解魔术数字,尽管它仍然很有用,谢谢!

No, magic numbers are non-obvious ones. 不,魔术数字不是显而易见的数字。 -1 , 0 , and 1 are generally obvious, but not always. -101通常是显而易见的,但并非总是如此。

In your case, neither of your snippets is obvious to me. 就您而言,您的片段都不对我显而易见。 Why is the width of your map data stored in an array? 为什么将地图数据的宽度存储在数组中?

Without seeing more code, I would prefer this: 在没有看到更多代码的情况下,我希望这样做:

auto GoRPG::MapData::GetWidth() {
    return mData.shape()[width_index]; 
}

I think you should have a constant defined for this case and not use a number. 我认为您应该为此情况定义一个常量,而不要使用数字。 0 is not always "magic", in instances where accessing the first element is the intuitive thing to do. 在访问第一个元素是很直观的事情的情况下,0并不总是“神奇”的。 Example: checking the first byte of a string, there's no reason to define a c_first_byte constant.) 示例:检查字符串的第一个字节,没有理由定义c_first_byte常量。)

But in your code, it would be even better to add a method to shape or mData named x() that returns the value that you want. 但是在您的代码中,最好添加一个形状为m x()的方法x()来返回所需的值。 There's no need to expose the internal representation of mData or shape to its users. 无需向用户公开mDatashape的内部表示。

The code does not compile though. 该代码虽然不能编译。 Since, you haven't used decltype to deduce the return type. 从那时起,您就没有使用decltype来推断返回类型。 Do all the shapes have the same width ? 所有形状的宽度都相同吗?

If yes, then should be OK. 如果是,则应该可以。 If not, then better approach could be to provide a default argument. 如果不是,那么更好的方法可能是提供默认参数。

  auto MapData::GetWidth(const size_t index = 0) -> decltype( mData.shape()[0]) { 
    return mData.shape()[index];  
  } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM