ホームページ  >  に質問  >  本文

c++ - 将函数作为类的成员应当遵从什么样的规范?

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

阿神阿神2712日前450

全員に返信(1)返信します

  • PHP中文网

    PHP中文网2017-04-17 15:25:08

    可以参考:C++ Core Guidelines

    类规则的第四条

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

    只有当函数需要直接对类成员变量访问的时候,才将函数作为成员函数,其他的,都应该作为辅助函数(helper function),这些辅助函数应该和类放在同一个命名空间里面。
    例如:

    namespace Chrono { // here we keep time-related services
    
        class Time { /* ... */ };
        class Date { /* ... */ };
    
        // helper functions:
        bool operator==(Date, Date);
        Date next_weekday(Date);
        // ...
    }

    对于问题中的Matrix类,这些函数都应该作为辅助函数。

    返事
    0
  • キャンセル返事