Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

c++ - 你如何在C ++中声明一个接口?(How do you declare an interface in C++?)

How do I setup a class that represents an interface?

(如何设置代表接口的类?)

Is this just an abstract base class?

(这只是一个抽象的基类吗?)

  ask by Aaron Fischer translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To expand on the answer by bradtgmurray , you may want to make one exception to the pure virtual method list of your interface by adding a virtual destructor.

(要扩展bradtgmurray的答案,您可能希望通过添加虚拟析构函数对接口的纯虚方法列表进行一个例外。)

This allows you to pass pointer ownership to another party without exposing the concrete derived class.

(这允许您将指针所有权传递给另一方,而不会暴露具体的派生类。)

The destructor doesn't have to do anything, because the interface doesn't have any concrete members.

(析构函数不必执行任何操作,因为接口没有任何具体成员。)

It might seem contradictory to define a function as both virtual and inline, but trust me - it isn't.

(将函数定义为虚拟和内联可能看起来很矛盾,但请相信我 - 事实并非如此。)

class IDemo
{
    public:
        virtual ~IDemo() {}
        virtual void OverrideMe() = 0;
};

class Parent
{
    public:
        virtual ~Parent();
};

class Child : public Parent, public IDemo
{
    public:
        virtual void OverrideMe()
        {
            //do stuff
        }
};

You don't have to include a body for the virtual destructor - it turns out some compilers have trouble optimizing an empty destructor and you're better off using the default.

(您不必为虚拟析构函数包含一个主体 - 事实证明,某些编译器在优化空析构函数时遇到问题,您最好使用默认析构函数。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...