【发布时间】:2012-02-27 10:35:25
【问题描述】:
我在我的项目中使用我的 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 获得)来获取默认值? 顺便说一句,这是授权的吗?
【问题讨论】:
-
“我怎么能……”——你不能。标准规定
this不能在这种情况下隐式或显式使用(8.3.6/8、8.3.6/9)。 -
ltjax: 是的,我自己没找到……我怀疑这应该已经在 SO :)
标签: c++ dynamic methods default-value overloading