C++ 在运行时向对象添加函数集合
我想做的是在我的代码中实现角色编程技术。我用的是C++。C++11很好 我需要的是能够定义一组函数。此集合不能具有状态 此集合的某些功能将被延迟/委派 e、 g.仅图示:C++ 在运行时向对象添加函数集合,c++,delegation,C++,Delegation,我想做的是在我的代码中实现角色编程技术。我用的是C++。C++11很好 我需要的是能够定义一组函数。此集合不能具有状态 此集合的某些功能将被延迟/委派 e、 g.仅图示: class ACCOUNT { int balance = 100; void withdraw(int amount) { balance -= amount; } } ACCOUNT savings_account; class SOURCEACCOUNT { void withdraw(int amoun
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的基类并进行转换,因为我想模拟运行时继承。帐户不知道有关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
};