c++静态成员

上图

这里的要增加新功能,count,当如果这样定义的化,在系统中,当读入第一个数据的时候,为x=4,y=5 count=1,读入第二个的时候,x=12,y=6,count=2;但第1个数据里面count还是为1,所以造成数据不统一。

之后

 

 之前是于对象里面的,现在是存储在类的存储空间,(静态存储空间)。

存储在专用空间,大家可以共同访问。

生命周期与main相同。

#include <iostream>
using namespace std;
class Point {
	int x, y;
	static int  count;
public :
	Point(int x = 0, int y = 0) :x(x), y(y)
	{
		count++;
	}
	~Point()
	{
		count--;
	}
	int getx() { return x; }
	int gety() { return y; }
	//若把showCount改为静态函数
	static  void showCount ()
	{
		cout << "obgect count=" << count << endl;
	}
	/*void showCount()
	{
		cout << "obgect count=" << count << endl;

	}*/
};
int Point::count = 0;//静态数据成员定义和初始化,使用类名限定。
int main()
{
	Point a(4, 5);
	cout << "point A:" << a.getx() << "," << a.gety();
	a.showCount();
	Point::showCount();//匹配tatic  void showCount ()

	Point b;
	cout << "Point b" << b.getx()<<"," << b.gety();
	b.showCount();
	return 0;
}

2,静态变量。

//若把showCount改为静态函数。、

则增加一种调用方式

a.showCount();(以前的)
    Point::showCount(new);

//若把showCount改为静态函数
	static  void showCount ()
	{
		cout << "obgect count=" << count << endl;
	}
	/*void showCount()
	{
		cout << "obgect count=" << count << endl;

	}*/
};
int Point::count = 0;//静态数据成员定义和初始化,使用类名限定。
int main()
{
	Point a(4, 5);
	cout << "point A:" << a.getx() << "," << a.gety();
	a.showCount();
	Point::showCount();

	Point b;
	cout << "Point b" << b.getx()<<"," << b.gety();
	b.showCount();
	return 0;
}

 3.

 

 同时有了新的问题

如果直接在Point::showCount();函数里输出x,y,

不可以

因为count在main之前就分配空间。

但调用Point::showCount();之后还没有像;a.showCount();一样为a所包含的x,y变量开辟空间。

要用也要在定义a类型之后才用。

3,复制构造函数

 就是赋值作用,系统自动调用,c++把它赋值的过程允许用户输入。从而产生更多操作可能性。

例如,如图。子啊复制构造函数里进行count'++。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值