C++第三次作业
类的静态成员
静态数据成员
在类中,如果某个属性为整个类所共有的,不属于任何一个具体对象,则采用**static**关键字来声明为静态成员。静态成员只有一个副本,由所有该类的对象共同维护和使用,从而实现了同一类不同对象之间的数据共享。**类属性是描述类的所有对象特征的一个数据项,对应任何对象实例,它的属性值还是相同的**。
例如,使用Point类,其数据成员count用于统计Point类的对象个数,如果不使用static静态数据成员,如下:
#include <iostream>
using namespace std;
class Point
{
private:
int x, y;
int count = 0;//未使用static
public:
Point(int X, int Y)
{
x = X;
y = Y;
count++;
}//构造函数
Point(Point& p)
{
x = p.x;
y = p.y;
count++;
}
~Point() { count--; }
int getX() { return x; }
int getY() { return y; }
void displayCount()
{
cout << "count = " << count << endl;
}
};
int main()
{
Point a(4, 5);
cout << "Point a : " << a.getX() << " and " << a.getY() << endl;
a.displayCount();
Point b(1, 2);
cout << "Point b : " << b.getX() << " and " << b.getY() << endl;
b.displayCount();
return 0;
}
-
预期结果:
Point a : 4 and 5
count = 1
Point b : 1 and 2
count = 2 -
但实际结果是:
![]()
-
如果给count加上static,使其成为静态数据成员,如下:
#include <iostream>
using namespace std;
class Point
{
private:
int x, y;
static int count;//使用static
public:
Point(int X, int Y)
{
x = X;
y = Y;
count++;
}//构造函数
Point(Point& p)
{
x = p.x;
y = p.y;
count++;
}//复制构造函数
~Point() { count--; }
int getX() { return x; }
int getY() { return y; }
void displayCount()
{
cout << "count = " << count << endl;
}
};
int Point::count = 0;
int main()
{
Point a(4, 5);
cout << "Point a : " << a.getX() << " and " << a.getY() << endl;
a.displayCount();
Point b(1, 2);
cout << "Point b : " << b.getX() << " and " << b.getY() << endl;
b.displayCount();
return 0;
}
结果为:

静态函数成员
静态函数可以直接访问该类的静态数据和函数成员,而不必通过对象名。访问非静态成员,必须通过对象名。一般情况下主要用来访问同一类的静态数据成员,维护对象之间共享的数据。
上面的程序可以改写为:
#include <iostream>
using namespace std;
class Point
{
private:
int x, y;
static int count;//使用static
public:
Point(int X, int Y)
{
x = X;
y = Y;
count++;
}//构造函数
Point(Point& p)
{
x = p.x;
y = p.y;
count++;
}//复制构造函数
~Point() { count--; }
int getX() { return x; }
int getY() { return y; }
static void displayCount()//静态函数成员
{
cout << "count = " << count << endl;
}
};
int Point::count = 0;
int main()
{
Point a(2, 7);
cout << "Point a : " << a.getX() << " and " << a.getY() << endl;
Point::displayCount();//未通过对象名调用函数
Point b(4, 9);
cout << "Point b : " << b.getX() << " and " << b.getY() << endl;
Point::displayCount();//未通过对象名调用函数
return 0;
}
结果同之前一样:



浙公网安备 33010602011771号