C++---类的静态成员变量和静态成员函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/XUCHEN1230/article/details/84961017
class Person
{
public :
	Person()
	{
		
	}
	static int m_Age ;	//加入static 就是静态成员变量,会共享数据;
	//静态成员变量,在类内声明,类外进行初始化;

}

int Person.m_Age = 0; //类外初始化实现;


//对属性进行修改:
void test01()
{
	Person p1;
	p1.m_Age = 10;
	Person p2;
	p2.m_Age = 20;
	
	cout<<"p1 = "<<p1.m_Age<<endl;
	cout<<"p2 = "<<p2.m_Age<<endl;
}

int main()
{
	test01();
	
	
	return 0;
}

证明:类中 static 变量,使p1 和 p2来共享对象;

访问静态静态成员变量的方式2,加对象名:
Person::m_Age

只要是用了这个成员变量的都是共享的;


关键:类内声明,类外实现,一般通过类名访问。

注意:
静态成员变量也是有权限的:

class Person
{
public :
	Person()
	{
		
	}
	
private:
    stactic int m_other;
};

int Person::m_other  = 20; //private 下的静态成员变量,也是在类外进行 初始化;

但是,不能在类外进行访问:

cout<<"other = "<<Person::m_other << endl; //这句话编译时不能通过的;
//私有权限在类外是不能访问的;

静态成员函数:

class Person
{
public :
	Person()
	{
		
	}
	//静态的成员函数:
	static void func()
	{
		cout<<"func调用"<<endl;
	}
	
private:
    stactic int m_other;
};

//静态成员函数的调用:

void test01()
{
	Person p1;
	
	Person p2;
	
	p1.func();
	p2.func();
	Person::func();
	
}

但是静态成员函数,不可以访问普通的成员变量;

例如:

class Person
{
public :
	Person()
	{
		
	}
	//静态的成员函数:
	
	int m_A;
	static void func()
	{
		m_A = 10;	//需要区分m_A,所以不能访问普通成员变量;
		cout<<"func调用"<<endl;
	}
	
private:
    stactic int m_other;
};

静态成员函数,可以访问静态成员变量:

class Person
{
public :
	Person()
	{
		
	}
	//静态的成员函数:
	static int m_Age;	//不需要做区分,可以访问;
	static void func()
	{
		cout<<"func调用"<<endl;
	}
	
private:
    stactic int m_other;
};


静态成员函数也是有权限的,私有的静态成员函数不能被访问;


普通成员函数,可以访问普通成员变量,也可以访问静态成员变量;
 

class Person
{
public :
	Person()
	{
		
	}
	//静态的成员函数:
	static int m_Age;	//不需要做区分,可以访问;
	static void func()
	{
		cout<<"func调用"<<endl;
	}
	void MyFunc()
	{
		m_A = 10;
		m_Age = 100;
		
		
	}
	
private:
    stactic int m_other;
};

猜你喜欢

转载自blog.csdn.net/XUCHEN1230/article/details/84961017