自由函数与成员函数 [英] Free function versus member function

查看:452
本文介绍了自由函数与成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

拥有一个自由函数(在匿名名称空间中并且只能在一个源文件中访问)并发送所有变量作为参数,而不是拥有一个没有任何参数并直接访问成员变量的私有类成员函数,有什么好处呢?谢谢!

What is the advantage of having a free function (in anonymous namespace and accessible only in a single source file) and sending all variables as parameters as opposed to having a private class member function free of any parameters and accessing member variables directly? Thanks!

标题:

 Class A {
    int myVariable;
    void DoSomething() {
       myVariable = 1;
    }
 };

来源:

 namespace {
    void DoSomething2(int &a) {
        a = 1;
    }
 }

 int A::SomeFunction() {
    DoSomething2(myVariable); // calling free function
    DoSomething(); // calling member fucntion
 }

如果您想让它们成为成员,那么如果我先调用一个不访问任何成员变量的函数,但是该函数调用另一个正在访问成员的函数,该怎么办?它们都应该是成员函数还是免费的?

If you prefer making them members then what if I have a case that I first call a function that is not accessing any member variables but that function calls another function which is accessing a member. Should they both be member functions or free?

推荐答案

看到以下问题: C ++成员函数与自由函数

see this question: Effective C++ Item 23 Prefer non-member non-friend functions to member functions and also C++ Member Functions vs Free Functions

您应该更喜欢自由功能,因为它会促进松散耦合.

You should prefer free functions, in the extent that it promotes loose coupling.

仅当它在您的班级上起作用并且认为它确实与您的班级紧密相关时,才考虑使其成为成员函数.

Consider making it a member function only if it works on the guts of your class, and that you consider it really really tied to your class.

这是 101 C ++编码标准一书的要点,该标准指出,与成员函数相比,更喜欢自由函数和静态函数.

It is a point of the book 101 C++ coding standards, which states to prefer free function and static function over member functions.

尽管这可能被认为是基于观点的,但它可以减少上课时间,并且可以将关注点分开.

Altough this may be considered opinion based, it allows to keep class little, and to seperate concerns.

答案指出:此规则的原因是,通过使用成员函数,您可能会过多地依赖于一个班级的内部细节."

This answer states: "the reason for this rule is that by using member functions you may rely too much on the internals of a class by accident."

这篇关于自由函数与成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆