关于static成员变量

一直以为对static成员变量还算了解。直到昨晚看了《Effective C++》3rd Item49,才发现自己其实什么都不懂,真是惭愧!所以写下这篇随笔,为以后定期回顾参考,也希望大家不要犯类似的错误。

先看以下代码:

#include <iostream>
using namespace std;

class Base{

             static int itest;

public:

              void Set(){

                               itest++;

              }

               void Show(){

                              cout << itest << endl;

              }

};


int Base::itest = 100;

class Derive: public Base{

};

class Derive2: public Base{

};


int _tmain(int argc, _TCHAR* argv[])
{
   Derive d1;
   Derive2 d2;

   d1.Set();
   d2.Set();

   d1.Show();
   d2.Show();

   return 0;
}
输出是:

102

102

我以前的理解既然Derive和Derive2是从Base派生的两个不同的类,那么他们从Base继承而来的static变量也应该是不同的两份拷贝。所以他们应该输出

101

101

而不是实际上的102.

唉,出现这样的错误看来还是自己的c++基础太差了。其实对于类的static成员变量它不单独属于任何派生类,static成员只存在一份。所有派生类包括基类均共享这唯一的一份。所以才出现了开始的输出结果。

下面的程序更加证实了我的错误:

#include <iostream>
using namespace std;

class Base{

 static int itest;

public:

 void Set(){

  itest++;

 }

 void Show(){

  cout << itest << endl;

 }

};

int Base::itest = 100;

class Derive: public Base{

};

class Derive2: public Base{

};

int _tmain(int argc, _TCHAR* argv[])
{
 Derive d1;
 Derive2 d2;

 cout << sizeof(Base) <<endl;

 cout << &(Base::itest) << endl;

 cout << sizeof( Derive ) << endl;

 cout << &(Derive::itest) << endl;

 cout << sizeof( Derive2) << endl;

 cout << &(Derive2::itest) << endl;

 return 0;

}

程序输出结果表明Base和Derive以及Derive2的大小都是1. 这个结果表明Base类的static成员变量并未包含在任何一个类空间中。

然而对于定义static变量的类有些时候我们还是希望每个从其派生出来的类都能包含单独的一份拷贝而不是与基类和其他派生类共享。 能不能实现这样的想法呢?

答案是肯定的。

先看以下代码然后我在做解释:

#include <iostream>
using namespace std;

template< typename _class >
class Base{

              static int itest;

public:

              void Set(){

                               itest++;

             }

            void Show(){

                              cout << itest << endl;

           }

};

template < typename _class >
int Base< _class >::itest = 100;

class Derive: public Base<Derive>{

};

class Derive2: public Base<Derive2>{

};


int _tmain(int argc, _TCHAR* argv[])
{
         Derive d1;
         Derive2 d2;

         d1.Set();
         d2.Set();

         d1.Show();
         d2.Show();

         return 0;
}

输出:

101

101

这次的输出是101,正是我想要的结果。为什么呢?

原因是这里用到了模板,我们用不同的参数Base<Derive>、Base<Derive2>去实例化了这个模板,这就意味着Derive和Derive2派生自两个完全不同的类。因而避开了先前讨论的问题。

模板Base中定义的类型参数在Base中并没有实际的用到,他存在的唯一价值就是为我们提供了标识Base类的机会。也就是我们可以通过指定不同的类型参数而从同一个模板得到完全不同的两个类型定义。 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值