C++ : call another method for default method argument

标签 c++ dynamic methods default-value overloading

我正在项目中使用 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/

相关文章:

java - Java 中的可见性关键字实际上是方法,就像在 Ruby 中一样吗?

C++ 11 智能指针的使用

c++ - Cuda 三重嵌套 for 循环赋值

c++ - 库会覆盖信号处理程序,但我需要按 CTRL+C 进行清理

c++ - 如何同时满足 gcc4.1.2 和 gcc 4.7.3

javascript - HTML 表单不传递从 jQuery 动态添加的输入

Perl:动态加载模块并访问导出的内容

jquery - 防止其他链接在 AJAX 调用期间工作

java - 如何调用我的方法

java - 搜索和排序值