开发者

quick question about static function in c++

开发者 https://www.devze.com 2023-02-14 10:58 出处:网络
static function in c++ SO, there can be only on开发者_如何学Goe instance of static function for this class. Right?In C++, a static member function is just like a normal, global function, except with

static function in c++

SO, there can be only on开发者_如何学Goe instance of static function for this class. Right?


In C++, a static member function is just like a normal, global function, except with respect to visibility of names:

  1. The name of the function is qualified with the class name.
  2. Like a friend function, a static member function has access to private and protected class members. Also like a friend function, however, it does not have a this pointer, so it only has access to those parts of objects to which you've given it access (e.g., passed as a parameter).
  3. (Thanks Alf): You can't declare any member function (static or otherwise) as extern "C".


A static member function (inside a class) means that you can call that function without creating an instance of the class first. This also means that the function cannot access any non-static data members (since there is no instance to grab the data from). e.g.

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_;
};


Making a function static allows it to be called without instantiating an instance of the class it belongs to. learncpp.com has some more on the subject and check out the following example which will fail to compile:

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;
}


Static functions can be called without actually creating a variable of that type, e.g.:

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. */
}
0

精彩评论

暂无评论...
验证码 换一张
取 消