美文网首页
(十九)C++篇-自定义类(四)-static

(十九)C++篇-自定义类(四)-static

作者: GoodTekken | 来源:发表于2022-07-05 09:29 被阅读0次

    static 成员是类的组成部分但不是任何对象的组成部分,因此,static 成员函数没有 this 指针。

    因为 static 成员不是任何对象的组成部分,所以 static 成员函数不能被声明为 const。毕竟,将成员函数声明为 const 就是承诺不会修改该函数所属的对象。 最后, static 成员函数也不能被声明为虚函数。

    (1)static数据成员
    static 数据成员可以声明为任意类型,可以是常量、引用、数组、类类型,等等。
    static 数据成员必须在类定义体的外部定义(正好一次)。
    static 成员不是通过类构造函数进行初始化,而是应该在定义时进行初始化。
    (保证对象正好定义一次的最好办法,就是将 static 数据成员的定义放在包含类非内联成员函数定义的文件中)

    (2)static数据函数
    静态数据函数可以使用类名直接调用。

    被 static 修饰的变量属于类变量,可以通过类名.变量名直接引用,而不需要 new 出一个类来
    被 static 修饰的方法属于类方法,可以通过类名.方法名直接引用,而不需要 new 出一个类来

    测试代码如下:

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    
    class Point
    {
    
    public:
        static int count;
        int Func();
        static void SayHello()
        {
        cout<<"Hello World!"<<endl;
        }
    };
    
    int Point::count=100;//类外定义+初始化
    
    int Point::Func()
    {
        count++;
        cout<<"count:"<<count<<endl;
        return count;
    }
    
    int main()
    {
        Point point1;
        Point::SayHello();
        point1.SayHello();
        point1.Func();
        point1.Func();
        return 0;
    }
    

    输出结果:

    tekken@tekken:~/C++WS$ ./a.out 
    Hello World!
    Hello World!
    count:101
    count:102
    

    相关文章

      网友评论

          本文标题:(十九)C++篇-自定义类(四)-static

          本文链接:https://www.haomeiwen.com/subject/lgtsbrtx.html