Implement a class that cannot be inherited

analyze

  Ordinary classes can be inherited, but when the constructor of this class is declared private, the class cannot be inherited, and objects of this type cannot be defined outside the class. How to solve this problem?

  Method 1: The construction of a class object is realized by the constructor. If the constructor is declared as a private or protected type, the constructor cannot be called outside the class, and the object cannot be defined in the class. In this regard, we can define a public interface in the class to return the object generated by the member function, and then when defining the class outside the class, we only need to call this function, but this has drawbacks, because outside the class, only the class can be used object to call this member function, so this interface should be declared static.

  Method 2: First define an auxiliary class AA, define its constructor as private, and then let BB virtual inherit AA (BB is also a friend class of AA, so that BB can use the construction of AA to synthesize its constructor) . At this time, the CC class cannot inherit the BB class, because the CC class will call the BB constructor first when it is initialized, but the BB virtual inherits AA. In order to avoid ambiguity, the CC must first call the AA constructor, and the AA constructor The function is private and invisible, causing the compiler to report an error.

accomplish

//方法一
class AA
{
private:
    AA()
    {}
public:
    static AA* GetAAObj()
    {
        return new AA;
    }
    static AA GetAAOBj()
    {
        return AA();
    }
protected:
    int _aa;
};

class BB : public AA
{

};
//方法二
class AA
{
    friend class BB;
private:
    AA(int aa)
        :_aa(aa)
    {}
protected:
    int _aa;
};

class BB : virtual public AA
{
public:
    BB(int bb)
        :AA(10)
        , _bb(bb)
    {}
protected:
    int _bb;
};

class CC : public BB
{
    CC(int cc)      
    :BB(20)       //AA的构造函数不可用,编译器报错
    , _cc(cc)
    {}
protected:
    int _cc;
};

describe

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325527834&siteId=291194637