c++ 成员函数 成员函数指针 委托 封装成对象

本文探讨了如何在C++中实现命令模式,特别是在利用成员函数作为命令执行逻辑方面。介绍了直接使用类和成员函数指针的方法,以及通过委托类来间接调用成员函数的过程,并进一步讨论了模板的运用。

struct ICommand
{
    virtual bool execute(const string& args)=0;
};
map<string, ICommand*> cmds;
class SaveCommand : public ICommand { 
virtual bool execute(const string& args) { cout << "save command\n"; }
};
cmds["save"] =  new SaveCommand ;
cmds["load"] = new LoadCommand ;

这些可以工作,但是类搞得比较多了,一个命令一个类哦

我是否可以把类的成员函数给搞到 cmds 里呢?

比如
class Model
{
public:
    bool Copy(const string& args);
    bool Paste(const string& args);
};

我想 
cmds["copy"] = &Model::Copy;
cmds["Paste"] = &Model::Paste;

嗯,它不能通过编译
我用成员函数指针,再来个中间类吧

class ModelCmdDelegate : public ICommand {
public:
    virtual bool execute(const string& args) {
        return (m->*exe)(args);
    }

    typedef bool (Model::ExeFunc)(const string& args);
    ExeFunc exe;
    Model* m; 
};

Model m;
ModelCmdDelegate* copycmd = new ModelCmdDelegate;
copycmd->m = &m;
copycmd->exe = &Model::Copy;
cmds["copy"] = copycmd ;

ModelCmdDelegate* pastecmd = new ModelCmdDelegate;
pastecmd->m = &m;
pastecmd->exe = &Model::Paste;
cmds["paste"] = pastecmd ;

这样可以解决问题了
我还可以写成模板,这样把各种类的成员函数都加进来 就方便多了
template<typename clsname>
class CmdDelegate : public ICommand {
    typedef bool (clsname::ExeFunc)(const string& args);
    CmdDelegate<clsname*>(ExeFunc e, clsname* o) : obj(o), exe(e) {}

public:
    virtual bool execute(const string& args) {
        return (obj->*exe)(args);
    }

    ExeFunc exe;
    clsname* obj; 
};

CmdDelegate<model*> cd = new CmdDelegate<model*>(&Model::Paste, &m);
cmds["paste"] = cd;






### Initialization File in Software Development Context In the realm of software development, an initialization file (often referred to as a config or ini file) plays a crucial role during system startup and operation. These files contain settings that dictate how applications behave upon launch and throughout their lifecycle. #### Purpose Initialization files serve multiple purposes: - **Configuration Storage**: Store user-defined parameters such as paths, ports, IDs, etc., ensuring flexibility without requiring code changes. - **Environment Adaptation**: Allow systems like ZooKeeper servers to adapt based on deployment environments through configurable options[^3]. - **Bootstrapping Information**: Provide essential instructions for initial program execution phases, including setting up necessary resources before main application logic begins executing. For example, BL1 handles critical early-stage operations post-boot by reading specific configurations from these files[^1]. #### Usage The utilization of initialization files varies across different platforms but generally involves defining key-value pairs within sections denoted by headers enclosed between square brackets `[SectionName]`. Here’s a simple demonstration using Python's configparser module to read/write INI-style configuration data: ```python import configparser config = configparser.ConfigParser() config.read('example.ini') print(config.sections()) # Output all section names found in 'example.ini' if not config.has_section('DEFAULT'): config.add_section('DEFAULT') config.set('DEFAULT', 'ServerAliveInterval', '45') with open('example.ini', 'w') as configfile: config.write(configfile) ``` This script demonstrates basic interaction with an `.ini` file containing various settings grouped under distinct headings. #### Troubleshooting When encountering issues related to initialization files, consider checking several common areas: - Verify syntax correctness according to expected format standards. - Ensure proper permissions exist so programs can access/read/write required entries. - Confirm compatibility among versions when upgrading components relying heavily on externalized properties. For instance, if facing problems configuring JVM heap sizes via `SGA_TARGET`, ensure appropriate values align well with overall memory constraints present in one's operational setup[^2]. --related questions-- 1. How do initialization files differ across operating systems? 2. What best practices should be followed while designing initialization files for large-scale distributed systems? 3. Can you provide examples of popular formats besides .ini used for storing configuration details? 4. In what scenarios might XML or JSON prove more advantageous over traditional flat-file structures for holding initialization info?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值