1

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'指针?

谢谢

4

1 回答 1

0

听起来您想创建一个SOURCEACCOUNT(或各种其他类),它引用 anACCOUNT并具有封闭类委托的一些方法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
};
于 2012-07-07T11:36:56.160 回答