C++的使用小教程7——类的静态成员
C++的使用小教程7——类的静态成员
- 1、什么是静态成员
- 2、类的静态数据实例
- 3、类的静态函数实例
学习好幸苦。
1、什么是静态成员
当我们声明一个类的成员为静态时,无论创建多少个类的对象,静态成员是共享的。
我们可以在类的外部对静态成员进行初始化,首先讲解静态数据的定义方式:
class Box
{
public:
static int Count;
……
};
则初始化方式如下:
// 初始化类 Box 的静态成员
int Box::Count = 0;
而类的静态函数的定义方式如下:
如果把函数成员被声明为静态的,静态函数可以在类对象不存在的情况下被调用,只要使用类名加范围解析运算符 :: 就可以访问静态函数。
静态成员函数只能访问静态成员数据、其他静态成员函数和类外部的其他函数。
2、类的静态数据实例
该例子讲述Count数据在两个类对象中的共享。
#include <iostream>
using namespace std;
class Box
{
public:
static int Count;
// 构造函数定义
Box(double l = 2.0, double b = 2.0, double h = 2.0)
{
cout << "Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
void countplus(){
Count++;
}
private:
double length; // 长度
double breadth; // 宽度
double height; // 高度
};
// 初始化静态变量
int Box::Count = 0;
int main(void)
{
/*创建Box1和Box2*/
Box Box1(3.3, 1.2, 1.5);
Box Box2(8.5, 6.0, 2.0);
Box1.countplus();
Box2.countplus();
/*最终Count = 2*/
cout << "Count = " << Box::Count << endl;
system("pause");
return 0;
}
应用结果为:
Constructor called.
Constructor called.
Count = 2
请按任意键继续. . .
3、类的静态函数实例
该例子讲述类的静态函数访问类的静态数据的例子。
#include <iostream>
using namespace std;
class Box
{
public:
static int Count;
// 构造函数定义
Box(double l = 2.0, double b = 2.0, double h = 2.0)
{
length = l;
breadth = b;
height = h;
}
void countplus(){
Count++;
}
static void getCount() {
cout << "Count = " << Count << endl;
}
private:
double length; // 长度
double breadth; // 宽度
double height; // 高度
};
// 初始化静态变量
int Box::Count = 0;
int main(void)
{
Box::getCount();
/*创建Box1和Box2*/
Box Box1(3.3, 1.2, 1.5);
Box Box2(8.5, 6.0, 2.0);
Box1.countplus();
Box2.countplus();
/*最终Count = 2*/
Box::getCount();
system("pause");
return 0;
}
应用结果为:
Count = 0
Count = 2
请按任意键继续. . .
还没有评论,来说两句吧...