首页 > 编程语言 > 详细

C和C++中static的比较

时间:2020-02-18 23:24:12      阅读:67      评论:0      收藏:0      [点我收藏+]
using namespace std;
class A{
        private:
                static int a;//由static修饰的变量仅仅是一个什么,不能在此处进行初始化,需要在类的外部初始化。
                void foo()
                {
                        a = 1;
                }
        public:
                void fuc(int b)
                {
                        foo();
                        a = b + 1;
                        cout << a << endl;
                }
};
int A::a = 0;
class B{
        public:
                static const int a = 0;//带上const的变量就可以在类中定义并初始化。
                static void foo1()
                {
                        cout << a << endl;
                }
};
//int B::a=1;
int main()
{
        A c;
        B b;
        c.fuc(2);
        B::foo1();
}

对比与上面的A类

//test1.c
#include <stdio.h>
static int a;
static void foo(int b)
{
        a = b + 1;
}
void fuc()
{
        foo(2);
        printf("%d\n",a);
}
//##############test2.c#################
extern void fuc();
int main()
{
        fuc();//此处可以通过fuc()函数简介的访问test2.c中的静态成员变量和成员函数。
        return 0;
}

C和C++中static的比较

原文:https://www.cnblogs.com/DXGG-Bond/p/12329101.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!