• 静态成员


    #include <iostream>
    #include <string.h>
    using namespace std;
    
    class Student
    {
    public:
    	Student(char *pName = "No name")
    	{
    		cout<<"create one student\n";
    		strcpy(name,pName);
    		cout<<name<<endl;
    		noOfStudent++;//静态成员:每创建一个对象,学生人数+1
    		cout<<noOfStudent<<endl<<endl;
    		pNext = pFirst;//每创建一个节点(对象),就把他挂在链首
    		pFirst = this;
    	}
    	~Student()
    	{
    		cout<<"destruct one student\n";
    		cout<<name<<endl;
    		noOfStudent--;//每析构一个对象,学生人数-1
    		cout<<noOfStudent<<endl<<endl;
    		if (pFirst == this)
    		{
    			//如果要删除链表结点,则只要链首指针指向下一个
    			pFirst = this->pNext;
    			return;
    		}
    		for (Student *pS = pFirst; pS; pS = pS->pNext)
    		{
    			if (pS->pNext == this)
    			{
    				//找到时,pS指向当前结点
    				pS->pNext = this->pNext;
    				return ;
    			}
    		}
    	}
    	//静态成员函数
    	static int number()
    	{
    		return noOfStudent;
    	}
    	static Student* FindName(char *pName)
    	{
    		for (Student *pS = pFirst; pS; pS = pS->pNext)
    		{
    			if (strcmp(pS->name,pName) == 0)
    			{
    				return pS;
    			}
    		}
    		return (Student*)0;//返回空指针
    	}
    protected:
    	static int noOfStudent;
    	static Student *pFirst;
    	Student *pNext;
    	char name[40];
    };
    
    //类声明只声明一个类的"尺寸与规格",并不进行实际的内存分配
    //静态数据成员在类声明外分配空间和初始化
    int Student::noOfStudent = 0;
    Student* Student::pFirst = 0;
    
    void fn()
    {
    	Student s1;
    	Student s2;
    	cout<<Student::number()<<endl;//调用静态成员函数用类名引导
    }
    
    Student* fn2()
    {
    	Student *pS = new Student("Jenny");
    	Student sb("Jone");
    	return pS;
    }
    
    
    
    int main()
    {
    	/*fn();
    	cout<<Student::number()<<endl;*/
    
    	/*Student sa("Jamsa");
    	Student *sb = fn2();
    	Student sc("Tracy");
    	delete sb;*/
    
    	Student s1("Randy");
    	Student s2("Jenny");
    	Student s3("Kinsey");
    	Student *pS = Student::FindName("Jenny");
    	if (pS)
    		cout<<"ok."<<endl;
    	else
    		cout<<"no find."<<endl;
    	return 0;
    }
    
  • 相关阅读:
    阿杜复博通知
    vim 配置文件 ,高亮+自动缩进+行号+折叠+优化
    网络课设总结(五)——利用CAsyncSocket进行异步通信
    网络课设总结(四)——利用CAsyncSocket进行异步通信
    网络课设总结(三)——VC++应用技巧
    ubuntu11.10下配置adsl上网
    反省
    cp命令“d”参数解释及实例
    网络课设总结(二)——VC开发环境
    SharePoint中如何获得当前用户的loginName
  • 原文地址:https://www.cnblogs.com/steady/p/1849178.html
Copyright © 2020-2023  润新知