簡體   English   中英

C++ - 為什么不能使用“const”限定符創建 static 成員 function

[英]C++ - Why static member function can't be created with 'const' qualifier

今天我遇到了一個問題。 我需要一個static成員 function, const不是必須的,而是更好的。 但是,我的努力沒有成功。 誰能說出為什么或如何?

當您將const限定符應用於非靜態成員 function 時,它會影響this指針。 For a const-qualified member function of class C , the this pointer is of type C const* , whereas for a member function that is not const-qualified, the this pointer is of type C* .

A static member function does not have a this pointer (such a function is not called on a particular instance of a class), so const qualification of a static member function doesn't make any sense.

我同意你的問題,但不幸的是 C++ 就是這樣設計的。 例如:

class A {
  int i;         //<--- accessed with 'this'
  static int s;  //<---- accessed without 'this'
public:
  static void foo ()  const // <-- imaginary const
  {}
};

到今天為止, const是在this的上下文中考慮的。 在某種程度上,它是狹窄的。 通過在this指針之外應用這個const可以使其更廣泛。
即“提議的” const也可能適用於static函數,它將限制static成員進行任何修改。

在示例代碼中,如果foo()可以設為const ,那么在該 function 中, A::s無法修改。 如果將此規則添加到標准中,我看不到任何語言副作用。 相反,有趣的是為什么不存在這樣的規則!

不幸的是,C++ 按照設計不接受它,但從邏輯上講,很少有用例可以很好地驗證。

function 是 class 級別有效(靜態)可能不會更改任何 static 數據,可能只是查詢數據應該是 const。 也許它應該像

if(Object)
    MakeThisConstant()
else
    MakeStaticDataConstant() // Only in the scope but static data cannot be constant so may be it should in some scenarios

不深入細節,這是因為可能有也可能沒有被 function 修改的 object,所以 const 對編譯器來說是模棱兩可的。

回想一下const保持對象不變,但這里可能有也可能沒有 object 來保持不變。

'const member function' 不允許修改調用它的 object,但不會在任何 object 上調用 static 成員函數。 scope分辨率算子直接使用。 因此,擁有一個 const static 成員 function 是沒有意義的,因此它是非法的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM