zoukankan      html  css  js  c++  java
  • const对象调用static成员函数

    例子1:

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Student
    {
    public:
        Student() {cnt++;}
        ~Student() {cnt--;}
        static int count(void);
    
        void showCnt(void) const
        {
            cout << "The student cnt: " << count() << endl;
        }
    private:
        static int cnt;
    };
    
    int Student::cnt = 0;
    
    // 静态成员函数
    int Student::count(void) { return cnt; } int main(int argc, char** argv) { const Student Mike; cout << "The student cnt: " << Mike.count() << endl; // const对象调用类的static成员函数 Mike.showCnt(); return 0; }

    启示:const对象调用是可以调用类的static成员函数的,但不能调用除const,static以外的类的成员函数。

    总结(转载如下)

    1.         静态数据成员static data member 是 类的,而不是仅属于某个对象的,该类的所有对象都可以调用它,类也可以调用。对象可调用它,但不是独占。生存期:编译时就分配,程序结束才释放空间。他只能在类体外初始化。作用域:与定义它的类的作用域相同,即与类同在。他的存在是为了对象间的共同交流。

    2.         静态成员函数Static member function 是为了调用static data member 而存在。Compile 不为他分配this 指针,所以他不能调用对象 的非static data member。当你非要调用 非Static data member 时,只要 指明对象就行了(因为没有compile 没有为类的static member function 指定 this 指针,所以引用 非静态成员变量时分不清是哪个对象的,当你指明对象来调用不就行了。)

  • 相关阅读:
    IDEA配置GIT
    夜游神安卓模拟器安装
    jira中使用eazyBI
    [Google Guava]学习--新集合类型Multimap
    [Google Guava]学习--新集合类型Multiset
    Java自己实现双向链表LinkList
    JVM学习之jstat使用方法
    Mycat+Mysql 插入数据报错 i[Err] 1064
    Windows配置mycat
    navicat cannot create file 文件名、目录名或卷标语法不正确 解决方法
  • 原文地址:https://www.cnblogs.com/Robotke1/p/3077946.html
Copyright © 2011-2022 走看看