【问题标题】:How to use a class member function as defualt value如何使用类成员函数作为默认值
【发布时间】:2019-12-25 15:39:41
【问题描述】:

我有这门课

class InventoryManagement
{
public:
    typedef void(InventoryManagement::*Action)(void);
    typedef void(InventoryManagement::*ActionWithReturn)(InventoryItem);

    void Initialize(int inventoryQty, int maxQty, ActionWithReturn onAdd = nullptr , Action onMaxQtyReach = nullptr, Action onQtyReset = nullptr, Action onSideChnage = nullptr);

    Action getStrategyOnMaxQtyReach();
    Action getStrategyOnQtyReset();
    Action getStrategyOnSideChange();
    ActionWithReturn getOnAdd();

private:

    // Private Functions Data members
    ActionWithReturn m_onAdd;
    Action m_OnSideChange;
    Action m_OnQtyReset;
    Action m_OnMaxQtyReach;


    // Default Function 
    void OnAddDefault(InventoryItem item) { }
    void OnMaxQtyReachDefault() { }
    void OnQtyResetDefault() { }
    void OnSideChangeDefault() { }
};

函数Initialize 设置Action 类型的数据成员。 我创建了注意的默认操作,我想将它们作为默认参数传递。如果用户没有向Initialize 发送任何函数指针,那么这些函数将被设置。

函数的签名是:

void Initialize(int inventoryQty, int maxQty, ActionWithReturn onAdd = nullptr , Action onMaxQtyReach = nullptr, Action onQtyReset = nullptr, Action onSideChnage = nullptr);

我试过了 void Initialize(int inventoryQty, int maxQty, ActionWithReturn onAdd = InventoryManagement::OnAddDefault , Action onMaxQtyReach = nullptr, Action onQtyReset = nullptr, Action onSideChnage = nullptr); 而不是nullptr,但编译器发出“调用没有对象参数的非静态成员函数”

【问题讨论】:

  • function Initialize then thosw function will set. wat? InventoryManagement::*OnAddDefault InventoryManagementOnAddDefault 是什么?提供minimal reproducible example
  • InventoryManagement::OnAddDefault可以是static吗?
  • @yaodav 请提供最小的完整代码。
  • 错误的意思就是它所说的:您正在尝试调用没有对象的非静态方法。但是,您没有发布的错误消息的实际来源。请提供minimal reproducible example
  • 很高兴您回答并按照我们的要求行事。但是,您需要 edit 您的问题以包含信息。评论用于要求澄清,问题必须包含所有相关信息。

标签: c++


【解决方案1】:

语法是&InventoryManagement::OnAddDefault:

void Initialize(
    int inventoryQty,
    int maxQty,
    ActionWithReturn onAdd = &InventoryManagement::OnAddDefault, // <-- 
    Action onMaxQtyReach = nullptr,
    //... etc
)

在边节点上,我鼓励您考虑使用构造函数而不是初始化方法。

【讨论】:

  • 谢谢,它有效,我知道正确的方法是在构造函数中,但我有一个限制
  • @yaodav 尝试添加,“InventoryManagement() = delete;”到你的班级。如果您认为没有演员是“我有的限制”,我认为您还没有根据该限制消除“演员”。
  • @2785528 当我写到我有一个限制是关于在 CTOR 中进行初始化而不是 int 函数 Initialize,
猜你喜欢
  • 2015-01-15
  • 2020-11-27
  • 2011-01-06
  • 1970-01-01
  • 1970-01-01
  • 2019-04-30
  • 1970-01-01
  • 2011-06-21
相关资源
最近更新 更多