c语言静态函数调用静态变量
Program 1:
程序1:
#include <iostream>
#include <stdlib.h>
using namespace std;
class Sample {
static int A;
public:
Sample()
{
A++;
}
static void fun()
{
cout << A << endl;
}
};
int Sample::A = 0;
int main()
{
void (*F_PTR)();
Sample S1, S2;
F_PTR = Sample::fun;
F_PTR();
return 0;
}
Output:
输出:
2
Explanation:
说明:
Here, we created a class Sample that contains a static data member A, constructor, and one static member.
在这里,我们创建了一个类Sample ,其中包含一个静态数据成员 A , 构造函数和一个静态成员 。
In the main() function, here we created the function pointer that is initialized with static member function of class, there is no need to mention static keyword with a function pointer. And, we created two objects S1 and S2 then we called static member function fun(). Then it will print 2 on the console screen.
在main()函数中,我们创建了使用类的静态成员函数初始化的函数指针,而无需在函数指针中提及static关键字。 并且,我们创建了两个对象S1和S2,然后调用了静态成员函数fun() 。 然后它将在控制台屏幕上打印2 。
Program 2:
程式2:
#include <iostream>
#include <stdlib.h>
using namespace std;
class Sample {
public:
static void fun1()
{
cout << "Hello ";
}
static void fun2()
{
cout << "Hiii ";
}
};
int main()
{
void (*F_PTR)();
Sample S1, S2;
F_PTR = Sample::fun1;
F_PTR();
F_PTR = Sample::fun2;
F_PTR();
return 0;
}
Output:
输出:
Hello Hiii
Explanation:
说明:
Here, we created a class Sample and two static member functions fun1() and fun2(). And, in the main() function, we created a function pointer that points fun1() and fun2() and called both functions. Then they will print "Hello Hiii" on the console screen.
在这里,我们创建了一个类Sample和两个静态成员函数fun1()和fun2() 。 并且,在main()函数中,我们创建了一个指向fun1()和fun2()的函数指针,并调用了这两个函数。 然后他们将在控制台屏幕上打印“ Hello Hiii” 。
Program 3:
程式3:
#include <iostream>
#include <stdlib.h>
using namespace std;
static class Sample {
public:
static void fun1()
{
cout << "Hello ";
}
static void fun2()
{
cout << "Hiii ";
}
};
int main()
{
void (*F_PTR)();
Sample S1, S2;
F_PTR = Sample::fun1;
F_PTR();
F_PTR = Sample::fun2;
F_PTR();
return 0;
}
Output:
输出:
main.cpp:5:1: error: a storage class can only be
specified for objects and functions
static class Sample {
^~~~~~
Explanation:
说明:
It will generate an error because we can only use static storage class with objects and functions.
它将产生一个错误,因为我们只能将静态存储类与对象和函数一起使用。
c语言静态函数调用静态变量