C和C++中static的比较

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;
}

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

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C和C++中static的比较

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/330194

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午5:27
下一篇 2023年3月1日 下午5:27

相关推荐