现在的位置: 首页 > 综合 > 正文

c/c++基础(二十四) 静态属性与静态方法

2019年09月12日 ⁄ 综合 ⁄ 共 1442字 ⁄ 字号 评论关闭

举个例子:

类A的声明与实现如下:

#pragma once
class A
{
	public:
		int count1;
		//static int count2=100;//error ,带有类内初始值设定项的成员必须为常量
		//const static int count3=100;//正确 
		static int count2;
	public:
		int getCount1();
		static int getCount2();

	public:
		A(void);
		~A(void);
};


#include "stdafx.h"
#include "A.h"


A::A(void):count1(99)
{
}


A::~A(void)
{
}

int A::getCount1()
{
	return count1;
};

//static int A::getCount2()//error,此处不能指定存储类,即类体外来实现静态成员函数,不能加static关键字
//{
//
//};

int A::getCount2()
{
	return count2*1000;
};

//初始化
int A::count2(1000);


测试文件如下:


// staticTest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include "A.h"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	A *a=new A;
	//访问非静态成员
	cout<<a->count1<<endl;	
	cout<<a->getCount1()<<endl;
	
	cout<<"------------------"<<endl;	

	//访问静态成员
	cout<<a->count2<<endl;	
	cout<<(*a).count2<<endl;
	cout<<A::count2<<endl;	
	
	cout<<a->getCount2()<<endl;	
	cout<<(*a).getCount2()<<endl;
	cout<<A::getCount2()<<endl;	

	delete(a);

	return 0;
}


打印结果:



注意事项:


1.静态数据成员不能在类中初始化,实际上类定义只是在描述对象的蓝图,在其中指定初值是不允许的。也不能在类的构造函数中初始化该成员,因为静态数据成员为类的各个对象共享,否则每次创建一个类的对象则静态数据成员都要被重新初始化。静态成员的值对所有的对象是一样的。静态成员可以被初始化,但只能在类体外进行初始化(通常在实现文件中进行初始化)。


2.静态成员函数在类外实现时候无须加static关键字,否则是错误的。


3.静态成员仍然遵循public,private,protected访问准则。


4.静态成员函数没有this指针,它不能返回非静态成员,因为除了对象会调用它外,类本身也可以调用。静态成员函数可以直接访问该类的静态数据和函数成员,而访问非静态数据成员必须通过参数传递的方式得到一个对象名,然后通过对象名来访问。


5.静态成员之间可以相互访问,包括静态成员函数访问静态数据成员和访问静态成员函数;非静态成员函数可以任意地访问静态成员函数和静态数据成员;静态成员函数不能访问非静态成员函数和非静态数据成员;调用静态成员函数,可以用成员访问操作符(.)和(->)为一个类的对象或指向类对象的指针调用静态成员函数;静态成员变量只能被静态成员函数调用,静态成员函数也是由同一类中的所有对象共用,只能调用静态成员变量和静态成员函数。




抱歉!评论已关闭.