Static Members:
c++中一些静态成员函数的有趣的事实
- 静态成员函数没有this指针
class Test{
private:
public:
static Test *fun() {
return *this;//compiler error
}
};
静态成员函数不能是虚函数
成员函数名相同且参数相同,如果其中一个是静态成员函数,那么他们就不能重载
class Test{
private:
public:
static void fun();
void fun();
};
- 静态成员函数不能被声明为const,const volatile,volatile
class Test{
private:
public:
static void fun() const{return;}
};
C++中静态成员
- 1
class A{
private:
public:
A() { cout << "A's constructer is called" << endl; }
};
class B{
private:
static A a;
public:
B() { cout << "B's constructer is called" << endl; }
};
int main() {
B b;
return 0;
}
这里仅仅调用B的构造函数,原因是静态成员变量必须在类声明中被声明,而不是定义。他们还必须在类外用范围解析符(::)定义
如果尝试不定义就使用静态成员变量,编译出错
如下:
- 2
class A{
private:
int x;
public:
A() { cout << "A's constructer is called" << endl; }
};
class B{
private:
static A a;
public:
B() { cout << "B's constructer is called" << endl; }
static A getA() { return a; }
};
int main() {
B b;
A a = b.getA();
return 0;
}
编译出错
- 3
class A{
private:
int x;
public:
A() { cout << "A's constructed is called " << endl; }
};
class B{
private:
static A a;
public:
B() { cout << "B's constructed is called " << endl; }
static A getA() { return a; }
};
A B::a;
int main() {
B b1,b2,b3;
A a = b1.getA();
return 0;
}
注意,这里B调用三次,而A调用一次,这是因为a是静态成员变量,为所有对象共享;另外静态成员变量可以不需对象即可访问。
补充,其实静态成员在main函数之前就已经被调用了,即在定义静态对象的时候,其已经生成。
class A{
private:
public:
A() { cout << "a's constructor called" << endl; }
};
class B{
private:
static A a;
public:
B() { cout << "b's constructor called" << endl; }
static A getA() { return a; }
};
A B::a;
int main() {
return 0;
}
输出
- 4
class A{
private:
int x;
public:
A() { cout << "A's constructed is called " << endl; }
};
class B{
private:
static A a;
public:
B() { cout << "B's constructed is called " << endl; }
static A getA() { return a; }
};
A B::a;
int main() {
A a = B::getA();
return 0;
}