- C++ 的类是个很神奇的的一种语法元素,在C++的语法中有个static的关键字,该关键字在类中的作用是修饰一个静态的变量。例如我们如果我们在想统计类创建的的个数,我们可以在类中定义static变量,每当新类出现的时候,该元素+1,delete某个元素的时候,该元素-1.即可实现统计类创建的的个数。
- static关键字是个很神奇的东西。他可以保存已经发生的一些数值。下次调用的时候可以再使用。
- 在基本的使用中可以保持变量内容持久:
- void test()
{
static int nm = 100;
nm = nm - 1;
cout << "test "<<nm << endl;
}
int main()
{
for (int i = 0; i < 10; i++)
{
test();
}
system(“pause”);
return 0;
}
运行结果:
test 99
test 98
test 97
test 96
test 95
test 94
test 93
test 92
test 91
test 90
请按任意键继续. . .
在类中使用为定义静态变量和静态成员函数,static成员函数和static变量属于整个类,不属于某个类对象。所以static成员函数没有thsi指针,没法调用非static成员函数和访问非static变量。
#include
using namespace std;
class Test
{
public:
Test()
{
n++;
sum += n;
}
static void set()
{
sum = 0;
n = 0;
//nn = 0;//对非静态成员非法引用
}
static int getSum()
{
return sum;
}
void print()
{
cout << getSum() << endl;//非static函数可以调用static函数。
}
private:
static int sum;
static int n;
int nn;
};
int Test::n = 0;
int Test::sum = 0;//静态成员变量需要必须手动初始化,否则编译会报错,而且必须在类外初始化
int main()
{
Test t1;
Test t2;
t1.print();
system(“pause”);
return 0;
}
那么我们可以利用static函数的特性来求1+2+3+4+5+…n的和。
#include
using namespace std;
class Test
{
public:
Test()
{
n++;
sum += n;//每当有一个类创建,位值n+1,sum+n
}
static void set()
{
sum = 0;
n = 0;
//nn = 0;//对非静态成员非法引用
}
static int getSum()
{
return sum;//返回N的和
}
void print()
{
cout << getSum() << endl;
}
private:
static int sum;
static int n;//定义两个静态变量,来储存和和位值
int nn;
};
int Test::n = 0;
int Test::sum = 0;//初始化两个静态变量为0.
int getsum(int n)
{
Test *t = new Test[n];
delete[] t;
t = nullptr;
return Test::getSum();
}
int main()
{
cout << getsum(100) << endl;
system(“pause”);
return 0;
}
static的确是一个神奇的东西
不用乘除算法,不用if、for、while、switch、case等关键字及条件语句,求1+2+3+4+5+....n的和
最新推荐文章于 2022-05-02 09:20:44 发布