【问题标题】:Correct way of storing function specific const options/variables?存储函数特定常量选项/变量的正确方法?
【发布时间】:2016-08-29 06:48:51
【问题描述】:

我正在学习如何格式化 C++,所以它是最干净的,但我不知道什么。

如何存储函数特定的常量变量? 我有以下两个想法:

我的第一个想法:

.cpp 内:

// ---------------------------------------------------------
// Purpose: Drawing the menu background.
// ---------------------------------------------------------
inline void DrawBackground() {
    static int BeginWidth = 80;
    static int EndWidth = 590;

    //usage of the BeginWidth and EndWidth
}

我的第二个想法:

.h 内:

const int BeginWidth = 80;
const int EndWidth = 590;

.cpp:

// ---------------------------------------------------------
// Purpose: Drawing the menu background.
// ---------------------------------------------------------
inline void DrawBackground() {
    //usage of the BeginWidth and EndWidth
}

这些想法是否正确?如果两者都正确,是否认为其中一个更合适?

【问题讨论】:

    标签: c++ variables options


    【解决方案1】:

    对于函数特定的常量变量,我会在函数顶部声明一个常量类型,如下所示:

    inline void DrawBackground() {
        const int BeginWidth = 80;
        const int EndWidth = 590;
    
        //usage of the BeginWidth and EndWidth
    }
    

    任何希望改变DrawBackground 行为的未来开发人员都会查看函数定义。为什么让它们引用标题?为什么要在一个地方使用定义混乱的标题?

    此外,在这个特定的示例中,将变量设为静态是很诱人的,因此它们只构造一次。但是,整数构造起来很简单,因此节省的空间最多可以忽略不计,最坏的情况会导致缓存未命中。

    【讨论】:

      猜你喜欢
      • 2018-03-25
      • 1970-01-01
      • 2019-10-31
      • 1970-01-01
      • 1970-01-01
      • 2022-07-07
      • 2013-06-24
      • 2015-05-05
      • 1970-01-01
      相关资源
      最近更新 更多