我正在项目中使用 Settings 类的默认参数,这样我声明的方法就会少一些。
例如,我声明了以下方法:
class Settings
{
// [..]
int getCurrentUserID(); // returns current user id
// you specify the user id
int setSetting( int value, int user_id );
// no user specified, use the current one, overloads the previous when called
// with only 1 argument
int setSetting( int value );
}
我想要的是这个简化版本:
class Settings
{
// [..]
int getCurrentUserID(); // returns current user id
// automatically selects the current user if no ID is provided
int setSetting( int value, int user_id = getCurrentUserID() );
}
但是我在编译时收到此错误:
cannot call member function ‘int Settings::getCurrentUserID()’ without object
我如何告诉编译器使用Setting对象的当前实例(可通过this获得)来获取默认值? 顺便问一下,这是授权的吗?
最佳答案
你有两个不错的选择。首先,假设 -1
不是合法的 user_id
:
class Settings
{
// [..]
int getCurrentUserID(); // returns current user id
// automatically selects the current user if no ID is provided
int setSetting( int value, int user_id = -1);
};
int Settings::setSetting( int value, int user_id )
{
if(user_id == -1) user_id = getCurrentUserID();
...
或者:
class Settings
{
// [..]
int getCurrentUserID(); // returns current user id
int setSetting( int value ) { return setSetting(value, getCurrentUserID() ); }
int setSetting( int value, int user_id );
};
关于C++ : call another method for default method argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9463551/