如何使用成员变量作为C ++中的默认参数? [英] How to use a member variable as a default argument in C++?

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

问题描述

我想为其中一个成员函数选择一个参数。当没有提供参数时,它将使用成员变量。

I want to make an argument for one of the member functions optional. When no argument is provided, it would use an member variable.

但是,当我试图编译它时,它显示错误:无效使用非静态数据成员Object :: initPos

However, when I tried to compile it it shows "error: invalid use of non-static data member 'Object::initPos'"

只是为了隔离问题,我尝试默认一个int类型,它编译正常。
我不知道我的代码有什么问题,以及如何使用成员函数作为默认值。

Just to isolate the problem, I tried defaulting an int type and it compiled fine. I wonder what is the problem with my code and how I could use a member function as default value.

感谢您的帮助!

Object.h

class Object
{
    public:
       ...
       void MoveTo(double speed, Point position);

    protected:
       Point initPos; 
       Point currPos;

};

Object.c

void Object::MoveTo(double speed, Point position = initPos)
{
    currPos = postion;
}

Point.h

class Point
{
    ...

    private:
       double x;
       double y;
       double z; 
};


推荐答案

成员函数的默认参数表达式只能取决于在类或全局范围内的东西。默认参数也必须在方法的声明中指定(即在头文件中)。

Default argument expressions for a member function can only depend on things that are in class or global scope. The default argument also has to be specified in the method's declaration (i.e. in the header file).

为了解决这个问题,你需要2个重载你的MoveTo方法。一个接受1个参数,另一个接受2个参数。采用1个参数的方法调用另一个方法,传递您认为默认的值。

To get around this, you need 2 overloads of your MoveTo method. One that takes 1 argument, and another that takes 2 arguments. The method taking 1 argument calls the other method, passing along the value that you consider as the default.

void Object::MoveTo(double speed)
{
    MoveTo(speed, initPos);
}

void Object::MoveTo(double speed, Point position)
{
    // Everything is done here.
}


$ b 调用 MoveTo(double,Point),它允许您编写 MoveTo 一次,从而尊重 DRY 原则。

Note that when you make MoveTo(double) call MoveTo(double, Point), it allows you to write the implementation of MoveTo only once, thereby respecting the DRY principle.

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

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