首頁  >  問答  >  主體

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

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

阿神阿神2712 天前451

全部回覆(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
  • 取消回覆