C++中static函数 类外定义的时候为什么不写static
巴扎黑
巴扎黑 2017-04-17 11:47:53
0
2
672
class A{
    static void foo();
}

void A::foo(){
    ....
}

为什么定义的时候不能写static了?

巴扎黑
巴扎黑

reply all(2)
伊谢尔伦

Imagine if you have two foo() functions in class A:

    class A{
        static void foo();
        void foo();
    };

In order to distinguish them, you only need to write static when defining:

    static void A::foo(){
        //....
    }
    void A::foo(){
        //....
    }

However, the C++ compiler does not take into account the presence or absence of the static keyword when distinguishing functions, but only looks at the function name, return type and parameter list. void foo(); and static void foo(); are considered duplicates. Declaration is prohibited, which means that there can only be one void foo(); function in a class, regardless of whether it is static or non-static. Why?
Then imagine that class A has another function void bar(); defined as follows:

    void A::bar(){
        //....
        foo();
        //....
    }

This way of writing is almost a convention. When calling function foo() within function bar(), you write foo() directly; instead of writing the static, const and other keywords used in function declaration, In this way, if you have a void foo() and a staic void foo(), the compiler cannot distinguish which foo() you are calling;
Since there can only be one void foo(), there is no need to write static again when you define it. The compiler already knows which function it is.

左手右手慢动作

When static is used to modify member variables or member functions, it can only be declared inside the class when it is declared. There is no need to add static when instantiating or defining it.

class A{
   static int n ;
};

int A::n = 123;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template