c++ - 有没有办法在声明变量后对其进行 constify ?

标签 c++ c constants

<分区>

Possible Duplicate:
Is there some ninja trick to make a variable constant after its declaration?

有时在 C 或 C++ 中,我们有一个可能是 const 的变量,但我们必须用几行代码来初始化它。

有没有办法告诉编译器,从一个函数的某个点开始,一些已经构造的变量必须被视为 const,直到它的作用域结束?

类似于:

int c = 0;
// the value of c is initialized here
switch(someVar) {
   case foo: c = 3; break;
   case bar: c = 4; break;
   default : c = 42; // what else?
}
// now c is constant
ASSUME_CONST_FROM_NOW(c) // some #pragma maybe?

我知道我可以在专用函数中初始化变量。这不是我真正想要的。

另一个例子:

int c = 0; int d = 0;
{ /*some block of code that initializes both c and d jointly*/ }
ASSUME_CONST_FROM_NOW(c, d)

没有函数可以在不创建结构或类的情况下一次返回两个值。

但这样的技巧可能很有用,可以让旧的、蹩脚的代码更容易理解,而无需进行太多重构。

最佳答案

是的。

将初始化放在一个函数中。

int getInitCValue(int const& someVar)
{
    // the value of c is initialized here
    switch(someVar)
    {
        case foo: return 3;
        case bar: return 4;
        default : return 42; // what else?
    }
}

int const c = getInitCValue(someVar);

编辑:回答修改后的问题。

你想初始化两个值:

std::pair<int,int> const value = initalizePairOfValues(someValue);
int const& c = value.first;
int const& d = value.second;

编辑 2:使用 Péter Török 删除的解决方案(Peter 如果你取消删除我会删除它)。

struct ConstValues
{
    ConstValues()
    {
         switch(....)
         // Initialize C/D
    }
    int const& getC() const {return c;}
    int const& getD() const {return d;}
    private:
       int c;
       int d;
};

关于c++ - 有没有办法在声明变量后对其进行 constify ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4689873/

相关文章:

c# - const 和非常量函数重载

java - 字符串常量中的参数

c++ - 使用 Xcode 11 和 macOS Catalina (zsh) 编译后 SFML 崩溃

c - 使用指针引用时的 block 级变量范围和生命线

CryptEncrypt 忽略 HASH?

c - 可执行和可重定位目标文件中的疑问

c++ - 转发模板参数的常量性,我应该使用转发引用吗?

c++ - 做两个用户定义的转换

c++ dll windows 插件体系结构方法

c++ - 如何在 Visual Studio 中查找语法错误的文件?