六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 41|回复: 0

中途需要产生const变量的一些方法

[复制链接]

升级  85%

884

主题

884

主题

884

主题

探花

Rank: 6Rank: 6

积分
2700
 楼主| 发表于 2013-1-26 13:45:40 | 显示全部楼层 |阅读模式
需求:

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) // 中途产生const变量
方法1:c++0xint const c = []() -> int {
int r;
switch(42) {
case 3:
    r = 1; break;
case 4:
    r = 2; break;
default:
    r = 23;
};
return r;
}();
方法2: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);
方法3:struct ConstValues
{
ConstValues()
{
switch(....)
// Initialize C/D
}
int const& getC() const {return c;}
int const& getD() const {return d;}
private:
int c;
int d;
};
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表