• C++静态成员函数和静态成员变量的探索


    静态数据成员属于类,非属于类对象,所以,定义位置就有了限制。

    静态数据成员要实际地分配空间,故不能在类的声明中定义(只能声明数据成员)。类声明只声明一个类的“尺寸和规格”,并不进行实际的内存分配,所以在类声明中写成定义是错误的。它也不能在头文件中类声明的外部定义,因为那会造成在多个使用该类的源文件中,对其重复定义。

    静态成员函数只能调用静态成员,要调用非静态成员,只能通过类对象,但一般成员函数可以调用静态成员函数。

    下面是一个综合性示例,对上面所说都有涉及:

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Student
    {
    private :
    	int _num;
    	int _score;
        
    
    public :
    
    	static string _classRoom;  //静态数据成员
    
    	//构造函数
    	Student(int num,int score):_num(num),_score(score){}
    
    	//在类内定义和声明函数  输出编号
    	void getNum(){
    	cout<<"the num is :"<<this->_num<<endl;
    	}
    	//在类内声明和在类外定义  输出成绩
    	void getScore();
    
    	//在类内声明静态函数  输出班级  如果要输出非静态成员需要传递对象 如同这个函数
        static	void getRoom1(Student s);
    	//在类内定义静态函数  输出班级  输出静态数据成员 如同此函数
    	static void  getRoom2(){
    	cout<<"the room is :"<<_classRoom<<endl;
    	}
    };
    //只能在类外对静态数据成员赋值  私有成员也不例外
    string Student::_classRoom="计科112班";
    
    //在类外定义的函数 用来输出成绩
    void Student::getScore(){
       cout<<"the score is :"<<this->_score<<endl;
    }
    //输出学生班级
    void Student::getRoom1(Student s){
      cout<<"the num   is :"<<s._num<<endl
    	  <<"the score is :"<<s._score<<endl
    	  <<"the score is :"<<_classRoom<<endl;
    }
    int main(){
    	Student stu(111,98);
    	stu.getNum();
    	stu.getScore();
    	stu.getRoom2();
    	Student::_classRoom="计算机专业";
    	Student::getRoom1(stu);
        return 0;
    }


    运行结果:




  • 相关阅读:
    人际交往的原则
    做事的八大原则
    做人要有三颗心,两种意,简称:三心二意
    基于docker Jenkins搭建持续集成自动化测试环境,管理、配置、运行 Node 节点与 Slave 分布式运行
    docker dockerfile使用详解
    OS + Linux Memory / NUMA / Non-Uniform Memory Access
    my live PC / ThinkPad_X13_Yoga_Gen_2 / 20W8001RUS
    0. 《RDMA杂谈》专栏索引
    RDMA read and write with IB verbs
    深入浅出全面解析RDMA
  • 原文地址:https://www.cnblogs.com/riasky/p/3430720.html
Copyright © 2020-2023  润新知