Can I use `abstract` keyword in C++ class

2020-02-11 23:26发布

Can we write abstract keyword in C++ class?

标签: c++ keyword
10条回答
Rolldiameter
2楼-- · 2020-02-11 23:42

As others point out, if you add a pure virtual function, the class becomes abstract.

However, if you want to implement an abstract base class with no pure virtual members, I find it useful to make the constructor protected. This way, you force the user to subclass the ABC to use it.

Example:

class Base
{
protected:
    Base()
    {
    }

public:
    void foo()
    {
    }

    void bar()
    {
    }
};

class Child : public Base
{
public:
    Child()
    {
    }
};
查看更多
疯言疯语
3楼-- · 2020-02-11 23:43

no, you need to have at least one pure virtual function in a class to be abstract.

Here is a good reference cplusplus.com

查看更多
别忘想泡老子
4楼-- · 2020-02-11 23:48

There is no keyword 'abstract' but a pure virtual function turns a class in to abstract class which one can extend and re use as an interface.

查看更多
SAY GOODBYE
5楼-- · 2020-02-11 23:48

No, C++ has no keyword abstract. However, you can write pure virtual functions; that's the C++ way of expressing abstract classes. It is a keyword introduced as part of the C++/CLI language spefication for the .NET framework. You need to have at least one pure virtual function in a class to be abstract.

class SomeClass {
public:
   virtual void pure_virtual() = 0;  // a pure virtual function
};
查看更多
冷血范
6楼-- · 2020-02-11 23:49

No.

Pure virtual functions, in C++, are declared as:

class X
{
    public:
        virtual void foo() = 0;
};

Any class having at least one of them is considered abstract.

查看更多
做个烂人
7楼-- · 2020-02-11 23:50

actually keyword abstract exists in C++ (VS2010 at least) and I found it can be used to declare a class/struct as non-instantiated.

struct X abstract {
    static int a;
    static void foX(){};
};
int X::a = 0;
struct Y abstract : X { // something static
};
struct Z : X { // regular class
};
int main() {
    X::foX();
    Z Zobj;
    X Xobj;    // error C3622
}

MSDN: https://msdn.microsoft.com/en-us/library/b0z6b513%28v=vs.110%29.aspx

查看更多
登录 后发表回答