在运行时向对象添加函数集合
Adding a collection of functions to an object at runtime
我想做的是在我的代码中实现角色编程技术。我正在使用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)
我愿意接受任何建议;我可以在 SOURCEACCOUNT 类中对函数进行外部或类似操作吗?C++11工会?C++11呼叫转移?更改"this"指针?
谢谢
听起来你想创建一个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
};
相关文章:
- 如何将函数集合传递给客户端类,以便将它们当作客户端类本身的成员使用
- 实现一个在集合上迭代的模板函数
- 尝试使用集合函数时出现分段错误
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 基于函数而不是集合的二分搜索或迭代器?
- 成员函数不能为集合迭代器和const_iterator的输入重载(但可以为其他 STL 迭代器重载)
- find() 函数对集合有效吗?
- 我们如何使用下面的集合构造函数构造设置元素
- 有没有一种单行方法来调用集合上的 lambda 函数
- 将all_of与 lambda 函数集合一起使用
- 异质集合调用派生类函数 c++
- 在集合上运行的函数模板,该集合具有默认的"transform"函数,该函数不执行任何操作
- 递归函数,用于使用位掩码 c++ 显示集合的所有子集
- C++集合方法:函数'setCost'不可行:'this'参数的类型'const value_type'
- C++:每当将元素添加到集合中时,如何调用函数
- 使用提升的集合中的成员函数代理
- 在声明'const'函数中循环访问具有'const_iterator'的集合会导致错误
- 避免集合的标头节点需要空构造函数
- 在运行时向对象添加函数集合
- 与个人比较函数集合具有相同的值