1.
在类里声明的类的静态成员只是起到一个说明作用,并不会分配成员的变量空间.必须另外在类外面进行声明.
例如,
int Boy::m = 0;
即使不进行初赋值,也要有这样一个定义语句:
int Boy:m;
因为只有这样,编译程序才分配了变量的空间.
否则,便会在链接的时候,出现:
undefined reference to `Boy::m' 这样的错误.
2.
尽管成员是在类的定义体之外定义的,但成员定义就好像它们是在类的作用域中一样。回忆一下,出现在类的定义体之外的成员定义必须指明成员出现在哪个类中: double Sales_item::avg_price( ) const {
if ( units_sold )
return revenue/units_sold; else
return 0; }
在这里,我们用完全限定名Sales_item::avg_price来指出这是类Sales_item作用域中的avg_price成员的定义。一旦看到成员的完全限定名,就知道该定义是在类作用域中。因为该定义是在类作用域中,所以我们可以引用revenue或units_sold,而不必写this->revenue或this->units_sold。
所以,当在类成员函数中访问静态成员变量时无需加上类名。而在对静态变量初始化时,如果位于类作用域之外,那么必须添加类名。
3.
When a static member variable is declared private in a class, how can it be defined?
In the very same way as you define a public static variable in your source(cpp) file.
int static_demo::a = 1;
Access specifiers will not give you error while defining the member. Access specifiers control the access of the member variables, defining a static variable is an excpetion which is allowed.
Compiles cleanly on Ideone here.
EDIT: To answer your Q after you posted code.
Your problem is not the definition of the static member. The error is because you are trying to access the private static member inside main
. You cannot do that.
Private members of a class can only be accessed inside the class member functions, the same rule applies even to static members. To be able to modify/access your static members you will have to add a member function function to your class and then modify/access the static member inside it.
4.
对象为什么能调用成员函数。是因为有this指针,每个成员函数都需要外界提供this指针,你把成员函数设成回调函数后,那系统要调用回调时,这个this从哪里来呢?所以一般情况下回调函数都设置为静态函数而非成员函数。
绑定回调的时候必须清楚是哪个函数,虚函数的动态方式是不现实的。
最后绑定成员函数并不是不可以的,boost::bind可以了解下它的原理。