Static Member of Derived Class

Static Member of Derived Class 原文 From http://www.codeproject.com/ by jsolutions_uk

View Code
#include <vector>
#include <iostream>

using namespace std;

class Base
{
public:
    virtual void doSomething() = 0;
};

template<typename T>
class DerivedTemplate : public Base
{
protected:
    static std::vector<int> listOfSomething;
};

template <typename _T>
std::vector<int> DerivedTemplate<_T>::listOfSomething;

class DerivedOne: public DerivedTemplate<DerivedOne>
{
public:
    DerivedOne()
    {
        if(listOfSomething.empty())
        {
            listOfSomething.push_back(1);
            listOfSomething.push_back(2);
        }
    };
    
    virtual void doSomething()
    {
        std::cout << "DerivedOne contains " << listOfSomething.size() << " items." << std::endl;
    };
};

class DerivedTwo: public DerivedTemplate<DerivedTwo>
{
public:
    DerivedTwo()
    {
        if(listOfSomething.empty())
        {
            listOfSomething.push_back(3);
            listOfSomething.push_back(4);
            listOfSomething.push_back(5);
        }
    };
    
    virtual void doSomething()
    {
        std::cout << "DerivedTwo contains " << listOfSomething.size() << " items." << std::endl;
    };
};

int main(int argc, char* argv[])
{
    DerivedOne oDerivedOne;
    DerivedTwo oDerivedTwo;
    
    oDerivedOne.doSomething();
    oDerivedTwo.doSomething();
    
    return 0;
}

 

posted on 2013-05-08 15:37  空娴  阅读(203)  评论(0编辑  收藏  举报

导航