wpcockroach

导航

函数、成员函数、友元函数:他们该以什么样的准则出现在我们的代码中?

终于可以在工作之余可以整理整理自己的知识网络了。最近正在花时间看别人整理好的关于C++ Idioms的相关内容,期间看到了Meyers关于如何界定你的函数应该是一个普通的函数,还是成员函数或者友元函数。牛人总结得就是到位,顺带就帖在这里。不过感觉没啥好解释的。

Given a class T and a function f:
if (f needs to be virtual)
{
    f should be a member function of T;
}
else if ( (f is operator>>) or (f is operator<<) or (f needs type conversions on its left-most argument) )
{
    f should be a non-member function;
    if (f needs access to non-public members of T)
    {
        f should be a friend of T;
    }
}
else if (f can be implemented via T's public interface)
{
    f should be a non-member function;
}
else
{
    f should be a member function of T;
}

posted on 2013-10-08 11:45  wpcockroach  阅读(291)  评论(0编辑  收藏  举报