84669 Lernen von Personen
152542 Lernen von Personen
20005 Lernen von Personen
5487 Lernen von Personen
7821 Lernen von Personen
359900 Lernen von Personen
3350 Lernen von Personen
180660 Lernen von Personen
48569 Lernen von Personen
18603 Lernen von Personen
40936 Lernen von Personen
1549 Lernen von Personen
1183 Lernen von Personen
32909 Lernen von Personen
class A{ static void foo(); } void A::foo(){ .... }
为什么定义的时候不能写static了?
设想如果你的class A里有两个foo()函数:
class A{ static void foo(); void foo(); };
这样为了区分它们,你在定义的时候才需要写static:
static void A::foo(){ //.... } void A::foo(){ //.... }
然而C++编译器在区分函数时不把有无static关键字考虑在内,而只看函数名,返回类型和参数表,void foo();和static void foo();被视为重复声明,是被禁止的,也就是说一个类里面只能有一个void foo();函数,不管它是static还是非static。为什么呢? 再设想class A有另一个函数void bar();定义如下:
void A::bar(){ //.... foo(); //.... }
这种写法差不多算是一种惯例吧,在函数bar()内调用函数foo()的时候是直接写foo();而不会写上函数声明时使用的static,const等关键字,这样如果你有个void foo()还有个staic void foo(),编译器是无法区分你调用的是哪个foo()的; 既然只能有一个void foo(),那么你在定义它的时候也就没必要再写一遍static了,编译器已经知道它是哪个函数了。
static用于修饰成员变量或成员函数时,只在声明时在类的内部声明即可,实例化或定义的时候不用加static。
class A{ static int n ; }; int A::n = 123;
设想如果你的class A里有两个foo()函数:
这样为了区分它们,你在定义的时候才需要写static:
然而C++编译器在区分函数时不把有无static关键字考虑在内,而只看函数名,返回类型和参数表,void foo();和static void foo();被视为重复声明,是被禁止的,也就是说一个类里面只能有一个void foo();函数,不管它是static还是非static。为什么呢?
再设想class A有另一个函数void bar();定义如下:
这种写法差不多算是一种惯例吧,在函数bar()内调用函数foo()的时候是直接写foo();而不会写上函数声明时使用的static,const等关键字,这样如果你有个void foo()还有个staic void foo(),编译器是无法区分你调用的是哪个foo()的;
既然只能有一个void foo(),那么你在定义它的时候也就没必要再写一遍static了,编译器已经知道它是哪个函数了。
static用于修饰成员变量或成员函数时,只在声明时在类的内部声明即可,实例化或定义的时候不用加static。