地球人都知道,一个类的不同对象共享同一个静态(static)成员:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
 
using namespace std;
 
class Base
{
public:
	void set(int n){m_data = n;}
	int get(){return m_data;}
private:
	int static m_data;
};
int Base::m_data = 0;
 
class Derived1: public Base{};
class Derived2: public Base{};
int 
main()
{
	Derived1 D1;
	Derived2 D2;
	D1.set(1);
	D2.set(2);
	cout<<D1.get()<<ends<<D2.get()<<endl;//~ 输出2 2
	return 0;
}

引入模板后:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;
 
template <class T>
class Base
{
public:
	void set(int n){m_data = n;}
	int get(){return m_data;}
private:
	int static m_data;
};
template <class T>
int Base<T>::m_data = 0;
 
class Derived1: public Base<Derived1>{};
class Derived2: public Base<Derived2>{};
int 
main()
{
	Derived1 D1;
	Derived2 D2;
	D1.set(1);
	D2.set(2);
	cout<<D1.get()<<ends<<D2.get()<<endl;//~ 输出1 2
	return 0;
}

其实,这只是一个小把戏,用不同类型实例化后的类完全是两个类型了,当然会拥有不同的静态成员!

Tags: ,,.
你好!除了代码,此处没有多少原创之物,皆为本人搜集、整理、总结之记录与心得,欢迎转载分享!转载时请尽量注明出处,将不胜感激。祝你健康、快乐!
Home

RFC: Request For Comments. Orz..

Be the first to comment on this entry.

Name(required)
Mail (required),(will not be published)
Website(recommended)