C++ STATIC 关键词
函数中的静态变量
#include <iostream>
#include <string>
using namespace std;
void demo() {
// static variable
static int count = 0;
cout << count << " ";
// value is updated and
// will be carried to next
// function calls
count++;
}
int main() {
for (int i=0; i<5; i++)
demo();
return 0;
}
//0 1 2 3 4
当变量声明为static时,空间将在程序的生命周期内分配。即使多次调用该函数,静态变量的空间也只分配一次,前一次调用中的变量值通过下一次函数调用传递。
类中的静态成员
#include<iostream>
using namespace std;
class Apple {
public:
static int i;
Apple(){
// Do nothing
};
};
int Apple::i = 1;
int main() {
Apple obj;
// prints value of i
cout << obj.i;
}
//1
由于声明为static的变量只被初始化一次,因为它们在单独的静态存储中分配了空间,因 此类中的静态变量由对象共享。对于不同的对象,不能有相同静态变量的多个副本。也是因为这个原因,静态变量不能使用构造函数初始化。
类中的静态方法
#include<iostream>
using namespace std;
class Apple {
public:
static void printMsg() {
cout<<"Welcome to Apple!";
}
};
// main function
int main() {
// invoking a static member function
Apple::printMsg();
}
//Welcome to Apple!
就像类中的静态数据成员或静态变量一样,静态成员函数也不依赖于类的对象。我们被允许使用对象和’.’来调用静态成员函数。但建议使用类名和范围解析运算符调用静态成员。
仅允许静态成员函数访问静态数据成员或其他静态成员函数,它们无法访问类的非静态数据成员或成员函数。
静态对象
类似于静态变量,对比下列两段代码:
#include<iostream>
using namespace std;
class Apple {
int i;
public:
Apple(){
i = 0;
cout << "Inside Constructor\\n";
}
~Apple(){
cout << "Inside Destructor\\n";
}
};
int main() {
int x = 0;
if (x==0)
Apple obj;
cout << "End of main\\n";
}
//Inside Constructor
//Inside Destructor
//End of main
#include<iostream>
using namespace std;
class Apple {
int i;
public:
Apple(){
i = 0;
cout << "Inside Constructor\\n";
}
~Apple(){
cout << "Inside Destructor\\n";
}
};
int main() {
int x = 0;
if (x==0)
static Apple obj;
cout << "End of main\\n";
}
//Inside Constructor
//End of main
//Inside Destructor