Home  >  Q&A  >  body text

c++对象模型 - C++中,可以通过私有化构造函数实现禁止创建栈对象,但是这样的类属于抽象类,又如何能够被实例化?

"只定义了protected构造函数的类也是抽象类。"
那么对于“禁止创建栈对象”这个问题,本身抽象类就不能实例化,是否问题本身就没有意义了呢?

迷茫迷茫2718 days ago530

reply all(2)I'll reply

  • 黄舟

    黄舟2017-04-17 12:06:07

    First clarify the "abstract class". It should be pointed out that abstract classes cannot be instantiated, but classes that cannot be instantiated are not necessarily abstract classes. For example:

    class A {
    private:
       A(){ }
       A(A&) { }
    };

    This is not called an abstract class because it does not contain pure virtual functions. If you want to use a class name to declare an object, it will not compile. This is the "prohibition of creating stack objects" mentioned in your question.
    But such a class is useful, add some code to it, such as

    class A {
    public:
        static A& getInstance(){
            static A a;
            return a;
        }
        void hello() { }
    private:
       A(){ }
       A(A&) { }
    };

    Although objects cannot be declared outside class A, it is completely possible within A itself, and then others can use it like this:

    A::getInstance().hello();

    This is the famous "single case pattern".

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 12:06:07

    In C++, the definition of an abstract class is a class that contains pure virtual functions, such as

    class Abstract
    {
        virtual void foo() = 0;
    };
    

    The so-called abstract class cannot instantiate objects, which refers to

    Abstract a;
    Abstract *pA = new Abstract();

    An error will be reported during compilation.

    And "a class that only defines a protected constructor is also an abstract class" is actually wrong. In other words, if this sentence is correct, then the abstract class here is a generalized abstract class, which means that here The abstract class borrows Java's saying that a class that cannot instantiate objects is considered an "abstract class". Because abstract classes are created to describe interfaces, and if the constructor is not a public class, the meaning of its existence may not be to accurately describe the interface.
    For specific examples, please refer to the singleton description of jk_v1. For C++ abstract classes, you cannot create an instance.

    reply
    0
  • Cancelreply