c++代码重构使用函数对象
c++ code refactoring using function objects
我有一些功能 returns 一个基于在启动时(在构造函数中)设置一次的值的值。由于这些条件值只设置一次,我不想一直检查它们。
有没有办法只做一次 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; }
};
我有一些功能 returns 一个基于在启动时(在构造函数中)设置一次的值的值。由于这些条件值只设置一次,我不想一直检查它们。 有没有办法只做一次 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; }
};