c语言静态函数调用静态变量_C ++静态变量和函数| 查找输出程序| 套装5

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关键字。 并且,我们创建了两个对象S1S2,然后调用了静态成员函数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.

它将产生一个错误,因为我们只能将静态存储类与对象和函数一起使用。

翻译自: https://www.includehelp.com/cpp-tutorial/static-variables-and-functions-find-output-programs-set-5.aspx

c语言静态函数调用静态变量

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值