默认参数作为非静态成员变量 [英] Default arguments as non-static member variables

查看:57
本文介绍了默认参数作为非静态成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个具有两个整数成员变量的类,以及一个具有两个可选参数的函数.如果提供了这些参数,则函数将返回它们的总和;否则,函数将返回它们的总和.如果未提供这些参数,则该函数将返回其两个成员变量的和.

I want to create a class, which has two integer member variables, and a function which has two optional arguments. If these arguments are supplied, the function returns the sum of them; if these arguments are not supplied, the function returns the sum of its two member variables.

这是代码:

class Foo
{
private:
    int x_;
    int y_;
public:
    Foo(int x, int y) : x_(x), y_(y){}
    int Bar(int a = x_, int b = y_)
    {
        int z = a + b;
        return z;
    }
};

但是,出现以下编译错误:

However, I get the following compilation error:

invalid use of non-static data member 'Foo::x_'
int x_;
    ^
invalid use of non-static data member 'Foo::y_'
int y_;
    ^

这表明成员变量必须是静态的才能在函数中用作默认参数.但我不希望它们是静态的...

This suggests that the member variables have to be static to use them in as default arguments in a function. But I do not want them to be static...

解决方案是什么?

推荐答案

重载 Bar :

int Bar()
{
    return x_ + y_;
}

int Bar(int x)
{
    return x + y_;
}

int Bar(int x, int y)
{
    return x + y;
}

感谢@ Jarod42的改进:

Thanks to @Jarod42 for this improvement:

int Bar(int a, int b)
{
    return a + b;
}

int Bar(int a)
{
    return Bar(a, y_);
}

int Bar()
{
    return Bar(x_, y_);
}

您要解决的现实问题比原始的将两个数字相加的问题更有可能从重构中受益.显然,这种行为与您希望通过默认参数实现的行为相同.

The real-world problem you're trying to solve is more likely to benefit from this refactoring than the original problem of summing two numbers. This behavior is more obviously identical to that you were hoping to achieve through default arguments.

这篇关于默认参数作为非静态成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆