2011-12-07 28 views
2

我想知道如果有一個「被廣泛接受,」在C命名約定++編寫這些方法時:C++命名約定用於修改參數和/或返回新實例的方法/函數?

class Transform3d { 
public: 
    // Apply rotation using a copy of toRotate and return it 
    Vector3d ApplyRotation(const Vector3d& toRotate) const; 

    // Apply rotation directly to toRotate 
    void ApplyRotationInPlace(Vector3d& toRotate) const; 

    // Apply rotation on this Transform3d instance (orientation quat) 
    void ApplyRotation(const Vector3d& toRotate); 

    //... 

    // Apply transformation using a copy of toTransform and return it 
    Transform3d ApplyTransform(const Vector3d& toTransform) const; 

    // Apply transformation directly to toTransform 
    void ApplyTransformInPlace(Vector3d& toTransform) const; 

private: 
    Quaternion orientation; 
    Vector3d position; 
}; 

是否有編寫C++方法與參數的修改,並返回新的實例涉及的一些準則(不修改參數)?

+1

一些純粹主義者可能會認爲** Transform3d **應該是一個不可變的類:) –

+1

從簽名中可以明顯看出'ApplyTransformInPlace'修改'toTransform',因爲它需要一個非const引用並返回'void'。額外的措辭只是混亂。 –

+2

請從您的函數名稱中刪除'Apply',它不會添加任何內容。 'rotate'和'transform'會傳遞消息。 –

回答

3

是的,你偶然發現它。這是const修飾符。

是否有寫C++方法與 參數修改交易並返回新的實例(不修改 對參數)的一些準則?

通過標記您的參數const,這正是您保證的。 const真的是爲開發者所準備的。

1

在您的示例中,它已經存在於語言本身中。按值返回=(新對象)在const ref =(不可修改)中傳遞 - 在非常量ref =(可修改)中傳遞。

我建議遠離裝飾方法名稱 - 因爲現在你已經使代碼維護翻了一番 - 每當你決定改變函數的工作方式時,都必須改變函數名稱。