C++ 6_类与对象_类与对象的其它特性 静态成员及友元
题目1. 验证静态数据成员
文件Point.h
#include <iostream>
using namespace std;
class Point
{
private:
double xPos, yPos;
public:
Point(double x=0, double y=0);
static int count;
};
文件Point.cpp
#include "Point.h"
int Point::count = 0;
Point::Point(double x, double y)
{
xPos = x;
yPos = y;
count++;
}
文件RunPoint.cpp
#include "Point.h"
#include <iostream>
using namespace std;
int main()
{
① Point a(2, 3), b;
② cout << Point::count << endl;
③ cout << a.count << endl;
④ cout << b.count << endl;
return 0;
}
(2) 在②前插入语句 Point ::count++ ;运行程序,再观察运行结果。a.count和b.count的值会跟着变吗?为什么?
答:会。因为如果将类的一个数据成员定义成静态型的,则该类的所有对象的该成员共用同一储存空间。
题目2
. 熟悉静态数据成员的使用,编程统计总成绩。运行结束后,理解程序结果截图的每一行。
#include “iostream”
using namespace std;
class Sample
{
int n;
static int sum; //静态成员
public:
Sample(int x=0) { n=x; }
void add( ){ sum+=n; }
void disp( )
{
cout<<“n=”<<n<<",sum="<<sum<<endl;
}
};
`
``
题目3 调试下列程序,熟悉静态成员函数的使用
#include
using namespace std;
运行结果