简体   繁体   English

C ++函数,返回指向抽象类的指针

[英]C++ function that returns a pointer to an abstract class

函数返回指向抽象类的指针是否有意义?

Of course, that's the whole point of polymorphism : to pass around and use pointers to abstract classes, regardless of what the concrete implementation is. 当然,这就是多态性的全部要点:无论具体实现是什么,都要传递并使用指向抽象类的指针。

Among others, the Factory Pattern typically returns a pointer to an abstract class. 其中,Factory Pattern通常返回指向抽象类的指针。

Yes it makes sense to manipulate pointer (or reference) to an abstract class in order to decouple the interface from the actual implementation and exploit the benefits of polymorphism . 是的,操纵指针(或引用)到抽象类是有意义的,以便将接口与实际实现分离并利用多态的好处。

But note that if the function is in charge of allocating the returned object (some kind of factory ), make sure to use a virtual destructor to be able to correctly delete the object from the abstract class pointer : 但请注意,如果函数负责分配返回的对象(某种工厂 ),请确保使用虚拟析构函数能够从抽象类指针中正确删除该对象:

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

class Derived : public Base {
  public:
    ~Derived() override {
        // Do some important cleanup
    }
};

Base* factory() {
    return new Derived;
}

Base* base = factory();
base->~Base(); // calls Derived::~Derived

Without the virtual destructor's of Base , the destructor of Derived would not have been called. 如果没有Base的虚析构函数, Derived的析构函数就不会被调用。

Yes it does make sense. 是的,它确实有意义。
It's like using interfaces. 这就像使用接口。

Sort of. 有点。 Say you have an abstract class named AClass , with a concrete implementation called CClass . 假设你有一个名为一个抽象类AClass ,一个叫具体实现CClass You could return a pointer to an instance of CClass which could be of type AClass* or CClass* . 您可以返回指向CClass实例的指针,该实例可以是AClass*CClass*类型。 However, as you can't instantiate an abstract class, you can't return a pointer to an instance of an abstract class. 但是,由于无法实例化抽象类,因此无法返回指向抽象类实例的指针。

However, if you return AClass* , your client will only be able to access the interface of AClass ; 但是,如果您返回AClass* ,您的客户端将只能访问AClass的接口; if they want to access CClass functionality not included in the interface of AClass , they will need to cast the pointer to be CClass* . 如果他们想访问CClass不包括在接口功能AClass ,他们将需要转换指针是CClass*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM