![](/img/trans.png)
[英]Question about npos and -1 for the output of a C++ function
[英]quick question about static function in c++
C ++中的靜態函數
因此,此類只能有一個靜態函數實例。 對?
在C ++中,靜態成員函數就像普通的全局函數一樣,只是名稱的可見性不同:
this
指針,因此它只能訪問您已授予其訪問權限的對象的那些部分(例如,作為參數傳遞)。 extern "C"
。 將函數設為靜態允許調用它而無需實例化其所屬類的實例。 learncpp.com上有更多有關此主題的內容,請查看以下示例,該示例將無法編譯:
class Foo
{
public:
static void Bar1();
void Bar2();
};
int main(int argc, char* argv[])
{
Foo::Bar1();
Foo x;
x.Bar2();
Foo::Bar2(); // <-- error C2352: 'Foo::Bar2' : illegal call of non-static member function
return 0;
}
靜態成員函數(在類內部)意味着您可以調用該函數而無需先創建類的實例。 這也意味着該函數無法訪問任何非靜態數據成員(因為沒有實例可以從中獲取數據)。 例如
class TestClass
{
public:
TestClass() {memberX_ = 10;}
~TestClass();
// This function can use staticX_ but not memberX_
static void staticFunction();
// This function can use both staticX_ and memberX_
void memberFunction();
private:
int memberX_;
static int staticX_;
};
無需實際創建該類型的變量即可調用靜態函數,例如:
class Foo
{
public:
static void Bar();
void SNAFU();
};
int main( void )
{
Foo::Bar(); /* Not necessary to create an instance of Foo in order to use Bar. */
Foo x;
x.SNAFU(); /* Necessary to create an instance of Foo in order to use SNAFU. */
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.