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

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

Program 1:

程序1:

#include <iostream>
#include <stdlib.h>
using namespace std;

class Sample {
    static int A;

public:
    Sample()
    {
        A++;
    }
};
int Sample::A = 0;

int main()
{
    Sample S1, S2, *S3;
    S3 = (Sample*)malloc(sizeof(Sample));

    cout << Sample::A;

    return 0;
}

Output:

输出:

main.cpp: In function ‘int main()’:
main.cpp:21:21: error: ‘int Sample::A’ is private within this context
     cout << Sample::A;
                     ^
main.cpp:14:5: note: declared private here
 int Sample::A = 0;
     ^~~~~~

Explanation:

说明:

In this program, we are trying to access the private data member outside the class and cannot access private data members outside the class.

在此程序中,我们尝试访问类外部的私有数据成员 ,并且无法访问类外部的私有数据成员。

Program 2:

程式2:

#include <iostream>
#include <stdlib.h>
using namespace std;

class Sample {
public:
    static int A;
    Sample()
    {
        A++;
    }
};
int Sample::A = 0;

int main()
{
    Sample S1, S2, *S3;
    S3 = (Sample*)malloc(sizeof(Sample));

    cout << Sample::A;

    return 0;
}

Output:

输出:

2

Explanation:

说明:

Here, we created a class Sample that contains one static data member and one default constructor. Here, we increased the value of the static member in the defined constructor.

在这里,我们创建了一个Sample类,其中包含一个静态数据成员和一个默认构造函数 。 在这里,我们增加了定义的构造函数中静态成员的值。

In the main() function, here we created two objects S1 and S2 and created one pointer S3, that initialized using malloc() function.  But the constructor will call for S1 and S2, but the constructor will not call when we use malloc() function, then the final value of A will be 2.

main()函数中,这里我们创建了两个对象S1S2,并创建了一个指针S3 ,并使用malloc()函数对其进行了初始化。 但是构造函数将调用S1S2 ,但是当我们使用malloc()函数时,构造函数将不会调用,那么A的最终值为2

Program 3:

程式3:

#include <iostream>
#include <stdlib.h>
using namespace std;

class Sample {
public:
    static int A;
    Sample()
    {
        A++;
    }
};
int Sample::A = 0;

int main()
{
    Sample S1, S2;
    new Sample();

    cout << Sample::A;

    return 0;
}

Output:

输出:

3

Explanation:

说明:

Here, we created a class Sample that contains one static data member and one default constructor. Here, we increased the value of the static member in the defined constructor.

在这里,我们创建了一个类Sample ,其中包含一个静态数据成员和一个默认构造函数。 在这里,我们增加了定义的构造函数中静态成员的值。

In the main() function, here we created two object S1, S2, and also created an object using a new Sample().

main()函数中,这里我们创建了两个对象S1S2 ,还使用新的Sample()创建了一个对象。

So, here constructor will call 3 times, then "3" will be printed on the console screen.

因此,这里的构造函数将调用3次,然后“ 3 ”将被打印在控制台屏幕上。

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值