[英]Copy ctor and copy assignment operator const keyword position
我最近注意到一些代碼示例中的const關鍵字在中間(來自受人尊敬的博客網站)轉移了,就像這樣:
X(X const& that) { .../... }
X& operator=(X const& other) { .../... }
這相當於這種更熟悉的語法嗎?
X(const X& that) { .../... }
X& operator=(const X& other) { .../... }
這樣切換“ const”的目的是什么?
1)放在哪里都無所謂const
: const int & == int const &
2)為什么呢? 這是助記符規則。
int * const
常量指針(* 之后的 const
)
int const *
-指向常量值的指針(int 之后的 const
)。
因此,其一致性。
這相當於這種更熟悉的語法嗎?
是的,這里的兩種語法是等效的。
X(X const& x)
X(const X& x)
這表示x
別名為X
類型的對象,但不能使用 x
更改該對象。 (如果您使用一些非const
別名,指針等,仍可以對其進行修改。)
您應該從右到左閱讀它: x
是X
類型為const
的對象的別名(或引用)。
我還建議您閱讀C ++常見問題解答:常量正確性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.