c++ - 将函数作为类的成员应当遵从什么样的规范?
阿神
阿神 2017-04-17 15:23:08
0
1
445

比如一个大小固定为4x4的矩阵类Matrix,针对矩阵的操作有许多,这些应当作为成员还是外部函数呢?

  • 矩阵的构造,比如单位矩阵、对角矩阵、旋转缩放平移投影等,这些应该作为const成员变量(部分)?还是作为构造函数?还是static成员函数?还是外部函数来产生?

  • 针对矩阵的操作非常多,比如矩阵的转置、矩阵求逆,应该作为成员还是外部函数?

  • 两个矩阵之间的操作,比如等价、合同,func(A, B)和A.func(B)哪个设计更好?

  • 运算符的重载,+、*、+=、*=、=、==这些应当作为成员函数还是作为友元函数?

阿神
阿神

闭关修行中......

reply all(1)
洪涛

You can refer to: C++ Core Guidelines

Article 4 of Class Rules

C.4: Make a function a member only if it needs direct access to the representation of a class

Only when the function needs to directly access the class member variables, the function should be used as a member function. Others should be used as helper functions. These helper functions should be placed in the same namespace as the class.
For example:

namespace Chrono { // here we keep time-related services

    class Time { /* ... */ };
    class Date { /* ... */ };

    // helper functions:
    bool operator==(Date, Date);
    Date next_weekday(Date);
    // ...
}

For the Matrix class in the question, these functions should be used as auxiliary functions.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!