指向另一个类

时间:2016-02-09 13:08:48

标签: c++ static-members non-static

我知道,这个问题已在这里提出,但我相信我的具体例子是独一无二的:

#include <functional>
#include <map>
#include <vector>

class Bar{
    public:
        static unsigned myFunc(const std::vector<std::string> &input){return 1;};
};

class Foo{
    friend class Bar;
    public:
        using CommandFunction = std::function<unsigned(const std::vector<std::string> &)>;
        std::map<std::string, CommandFunction> Commands;
};

int main(){
    Foo oFoo;
    Bar oBar;
    oFoo.Commands["myFunc"] = oBar.myFunc;
    return 0;
}

我想使myFunc函数非静态,因此它将能够访问Bar类的私有成员。但我不知道如何实现这个想法。简单地删除static关键字显然会在编译期间引发错误(无效使用非静态函数)。有没有&#39;清洁&#39;解决这个问题的方法?通过&#39; clean&#39;我的意思是不使用全局变量和对象。

更新

我想我需要澄清上面描述的设计的目的。 我正在使用GNU readline库的包装器。它由Foo类表示。基本上它在Commands映射中包含一组函数指针,并根据用户输入执行它们。

Bar类是一组共享公共资源的函数(Bar类的私有成员)。

1 个答案:

答案 0 :(得分:0)

Lambda可以为您提供解决方案:

class Bar{
    public:
        std::function<unsigned(const std::vector<std::string>&)> myFunc{ [](const std::vector<std::string>& x){return 1;}};

};