参考书目:C/C++规范设计简明教程,P323
目的:学习、测试静态类的使用。
第一步:建立工程。
第二步:添加Rect类。
头文件Rect.h为
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
using namespace std;
class Rect
{
public:
Rect();
Rect(int length, int width);
int getArea();
void display() const; //定义常成员函数,不能改变数据成员的值
void displayShared();
public:
//特设共享信息访问控制为公用,同一个类定义的对象共用
static int nums;
static int areas;
private:
int length; //长
int width; //宽
};
源文件Rect.cpp为
#include "Rect.h"
int Rect::nums = 0; //初始化静态数据
int Rect::areas = 0; //初始化静态数据
Rect::Rect() //构造函数1
{
length = 0;
width = 0;
nums++; //个数增加
}
Rect::Rect(int length, int width)
{
this->length = length;
this->width = width;
nums++;
areas = areas + getArea(); //面积增加
}
int Rect::getArea()
{
return (length * width);
}
void Rect::display() const //定义常成员函数,不能改变数据成员的值
{
cout << "矩形长度为:" << length;
cout << "矩形宽度为:" << width;
cout << endl;
}
void Rect::displayShared()
{
cout << "生成的矩形对象总个数为:" << nums;
cout << "生成的矩形对象的总面积数为:" << areas;
cout << endl;
}
第三步:主文件
//测试静态数据成员
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "Rect.h"
using namespace std;
int main()
{
cout << "Hello World!\n";
Rect r1(3, 4); //面积为3*4 =12
r1.display();
r1.displayShared(); //调用成员函数,显示共享
cout << r1.nums << " " << r1.areas << endl; //通过任意对象访问静态类成员
cout <<Rect::nums << " " << Rect::areas << endl; //通过类访问静态类成员
Rect r2(4, 5); //面积为4*4 =20
r2.display();
r2.displayShared(); //调用成员函数,显示共享
getchar();
}
运行结果如下: