2012-07-07 69 views
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作为计价基类,做一个演员,我想模拟运行期间继承的。 (帐户不知道SOURCEACCOUNT)

我对任何建议打开;我可以在SOURCEACCOUNT类中使用外部函数还是类似的函数? C++ 11联合? C++ 11呼叫转移?改变'这个'指针?

三江源

回答

0

这听起来像你想创建一个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 
}; 
+0

Thankyou夸姆拉纳! – 2012-07-07 21:03:55