使用函数对象重构 C++ 代码
c++ code refactoring using function objects
我有一些功能,可以根据启动时(在构造函数中)设置的值返回值。由于这些条件值只设置一次,我不想一直检查它们。有没有办法只做一次if-check,然后不使用函数对象或其他机制一次又一次地做?
class MyValue {
bool myVal; //set only once in the constructor
int myval1; //often updates
int myval2; //often updates
myValue(bool val, int val1, int val2)
{
myVal = val; // only place where myVal is set
// this value changes often in other functions not shown here
myval1 = val1;
// this value changes often in other functions not shown here
myval2 = val2;
}
int GetMyValue() //often called
{
if(myval) /* Is there a way I dont have to do an if check here?
and simply write a return statement? */
return myval1;
return myval2;
}
};
使用指针:
class MyValue
{
int* myVal;
int myval1; //often updates
int myval2; //often updates
myValue(bool val, int val1, int val2)
{
if (val) {
myVal = &myval1;
} else {
myVal = &myval2
}
myval1 = val1;
myval2 = val2;
}
int GetMyValue() //often called
{
return *myval;
}
};
(甚至更好的参考,如Rabbid76答案)
使用对myval1
或myval2
引用的成员,引用必须在构造函数中初始化一次:
class MyValue
{
bool myVal; //set only once in the constructor
int myval1; //often updates
int myval2; //often updates
int &valref;
public:
MyValue( bool val, int val1, int val2 )
: myVal( val )
, myval1( val1 )
, myval2( val2 )
, valref( val ? myval1 : myval2 )
{}
int GetMyVal() { return valref; }
};
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 为什么在这个代码结束循环中没有得到结束
- 在c代码之间共享数据的最佳方式
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值