如何使用一个成员变量在C ++默认参数? [英] How to use an member variable as a default argument in C++?

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

问题描述

我想打一个论据的成员函数任选其一。当没有提供参数,它会用一个成员变量。

然而,当我试图编译它,它显示的错误:无效使用非静态数据成员的对象:: initPos

只是为了隔离问题,我试着违约int型,它编译罚款。
我不知道什么是我的code和我怎么可以用一个成员函数作为默认值的问题。

感谢您的帮助!

Object.h

 类对象
{
    上市:
       ...
       虚空通过MoveTo(双速,位置);    保护:
       点initPos;
       点currPos;};

Object.c

 无效对象::通过MoveTo(双速,点位= initPos)
{
    currPos =现在的位置;
}

Point.h

 类Point
{
    ...    私人的:
       双X;
       双Y;
       双Z者除外;
};


解决方案

有关成员函数的默认参数的前pressions只能依靠事情是在课堂上或全局范围。默认参数也有在方法的声明中指定(即在头文件)。

要解决这个问题,就需要2重载您通过MoveTo方法。一个需要1参数,另一个需要两个参数。服用1参数的方法调用其他方法,以及你认为作为默认值传递。

 无效对象::通过MoveTo(倍速)
{
    通过MoveTo(速度,initPos);
}无效对象::通过MoveTo(双速,位置)
{
    //一切都在这里完成。
}

请注意,当您通过MoveTo(双)通话通过MoveTo(双,点),它可以让你写通过MoveTo 只有一次,从而尊重 DRY 原则。

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

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

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.

Thank you for your help!

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).

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.
}

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天全站免登陆