gpt4 book ai didi

c++ - 在运行时向对象添加函数集合

转载 作者:太空宇宙 更新时间:2023-11-04 14:15:53 24 4
gpt4 key购买 nike

我喜欢做的是在我的代码中实现角色编程技术。我正在使用 C++。 C++11 没问题。

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

这个集合的一些功能将被推迟/委托(delegate)。

例如(仅供引用:)

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 union ? C++11 调用转移?更改“this”指针?

谢谢

最佳答案

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

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
};

关于c++ - 在运行时向对象添加函数集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11374379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com