【问题标题】:Adding a collection of functions to an object at runtime在运行时向对象添加函数集合
【发布时间】:2012-07-07 15:09:01
【问题描述】:

id 喜欢在我的代码中实现角色编程技术。我正在使用 C++。 C++11 很好。

我需要的是能够定义一组函数。此集合不能有状态。

此集合的某些功能将被推迟/委托。

例如(仅供说明:)

class ACCOUNT {
  int balance = 100;
  void withdraw(int amount) { balance -= amount; }
}

ACCOUNT savings_account;

class SOURCEACCOUNT {
  void withdraw(int amount); // Deferred.
  void deposit_wages() { this->withdraw(10); }
  void change_pin() { this->deposit_wages(); }
}

SOURCEACCOUNT *s;
s = savings_account; 

// s is actually the savings_account obj,
// But i can call SOURCEACCOUNT methods.
s->withdraw(...);
s->deposit();
s->change_pin();

我不想包含 SOURCEACCOUNT 作为 ACCOUNT 的基类并进行强制转换,因为我想模拟运行时继承。 (ACCOUNT 不知道 SOURCEACCOUNT)

我愿意接受任何建议;我可以 extern 或类似 SOURCEACCOUNT 类中的函数吗? C++11 联合? C++11 呼叫转移?改变'this'指针?

谢谢

【问题讨论】:

    标签: c++ delegation


    【解决方案1】:

    听起来你想创建一个SOURCEACCOUNT(或各种其他类),它引用ACCOUNT,并有一些封闭类委托给ACCOUNT的方法:

    class SOURCEACCOUNT{
      ACCOUNT& account;
    public:
      explicit SOURCEACCOUNT(ACCOUNT& a):account(a){}
      void withdraw(int amount){ account.withdraw(amount); }
      // other methods which can either call methods of this class
      // or delegate to account
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-19
      • 2015-03-24
      • 2011-12-10
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多