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

查看:29
本文介绍了如何在 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.

感谢您的帮助!

对象.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;
}

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

要解决此问题,您需要对 MoveTo 方法进行 2 次重载.一个接受 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.
}

注意,当你让MoveTo(double)调用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天全站免登陆