Prevent class inheritance in C++

see: http://stackoverflow.com/questions/2184133/prevent-class-inheritance-in-c

倾向于使用private constructor and non-virtual destructor.

#include <iostream>
using namespace std;

class CBase
{
        public:
                static CBase* CreateInstance() 
                { 
                        CBase* b1 = new CBase();
                        return b1;
                }
        private:
                CBase() { }
                CBase(const CBase &c) { }
                CBase& operator=(const CBase &c) { }
};

class CC : public CBase
{
};

int main()
{
        CC c;
        return 0;
}

编译:

/home/a/j/nomad2:g++ Y.CPP
Y.CPP: In constructor 'CC::CC()':
Y.CPP:13: error: 'CBase::CBase()' is private
Y.CPP:19: error: within this context
Y.CPP: In function 'int main()':
Y.CPP:24: note: synthesized method 'CC::CC()' first required here 


你可能感兴趣的:(C++,c,function,Class,inheritance,Constructor)