C++中成员函数的声明与调用

成员函数的语法有点让人困惑,记录在此。
如下的一个类,有两个成员函数,形参相同:

struct foo
{
    std::string msg{};
    foo(const char* msg) : msg(msg)
    {}
    void printInfo()const
    {
        cout << msg << endl;
    }
    void sayHello()const
    {
        cout << "hello" << endl;
    }
};

成员函数的声明:

typedef void(foo.myPF*)()const;
//or
using myPF = void(foo.*)()const;

调用:

void test()
{
    std::vector vec{"a","b","c","d"};
    using mem_funPtr = void(foo::*)()const;
    mem_funPtr mfp = &foo::printInfo;
    for_each(vec.begin(), vec.end(), std::bind(mfp,std::placeholders::_1));
    mfp = &foo::sayHello;
    foo bar("this is a test class.");
    (bar.*mfp)();
    mfp = &foo::printInfo;
    auto pBar = &bar;
    (pBar->*mfp)();
}

输出:

a
b
c
d
hello
this is a test class.

尤其在模版中,如果遇到如下的调用形式,就不会很奇怪了。
不用std::bind也可以调用成员函数了:

using myPF = void(foo::*)()const;
template
void call(const foo& obj)
{
    (obj.*PF)();
}

void test()
{
    std::vector vec{"a","b","c","d"};
    for_each(vec.begin(), vec.end(), call<&foo::printInfo>);
}

你可能感兴趣的:(C++中成员函数的声明与调用)