如何在不使用new和delete的情况下实例化抽象类?
考虑以下代码,
class Interface
{
public:
Interface(){}
virtual ~Interface(){}
virtual void method1() = 0;
virtual void method2() = 0;
};
class Concrete : public Interface
{
private:
int myMember;
public:
Concrete(){}
~Concrete(){}
void method1();
void method2();
};
void Concrete::method1()
{
// Your implementation
}
void Concrete::method2()
{
// Your implementation
}
int main(void)
{
Interface *f = new Concrete();
f->method1();
f->method2();
delete f;
return 0;
}
在笔者使用的Interface *f = new Concrete();实例在主函数一个抽象类,后来他用delete f;,但这个问题new和delete是,我不喜欢他们。有没有其他方法来实例化这个类?
回答
您需要一个指向对象的指针或引用才能使多态工作,但您可以以任何您想要的方式创建该对象。
Concrete c;
c.method1(); // no polymorphism, using concrete directly
c.method2();
Interface* f = &c;
f->method1(); // polymorphism through Interface pointer
f->method2();
Interface& f2 = c;
f2.method1(); // polymorphism through reference
f2.method2();
避免手工的另一种方法new,并delete是使用智能指针。
#include <memory>
std::unique_ptr<Interface> upf = std::make_unique<Concrete>();
upf->method1();
upf->method2();