"只定義了protected構造函數(shù)的類也是抽象類。"
那么對于“禁止創(chuàng)建棧對象”這個問題,本身抽象類就不能實例化,是否問題本身就沒有意義了呢?
業(yè)精于勤,荒于嬉;行成于思,毀于隨。
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".
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.