简体   繁体   English

算法是成员函数还是非成员函数?

[英]Algorithms as member or non-member functions?

I have a simple data structure, a triangular matrix indexed by k and l , where l runs from 1 to N and k runs from 1 to l : 我有一个简单的数据结构,一个由kl索引的三角矩阵,其中l1Nk1l

template<int N> class triangular_matrix {
    std::vector<int> elem;
public:
    int& operator()(int k, int l) {
        return elem[(N * (N + 1) - l * (l + 1)) / 2 + k - 1];
    }
};

I also have several algorithms operating on this data structure. 我也有几种针对这种数据结构的算法。 All of them access triangular_matrix only via operator() . 它们都只能通过operator()来访问triangular_matrix

What are the pros and cons of making these algorithms member functions of triangular_matrix instead of making them non-member functions (in a non-global namespace)? 是什么使得这些算法的成员函数的利弊triangular_matrix ,而不是使他们非成员函数(在非全局命名空间)?

In C++ it's common to put everything that doesn't have to be a member function in a non-member function. 在C ++中是常见的把不必须是在非成员函数成员函数的一切。 Herb Sutter wrote a nice article about it a while back. 赫伯·萨特(Herb Sutter)前一段时间写了一篇不错的文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM