gpt4 book ai didi

c++ - 类有虚方法但非虚析构函数C++

转载 作者:可可西里 更新时间:2023-11-01 18:20:42 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
GNU compiler warning “class has virtual functions but non-virtual destructor”

我正在为两个类编写一个接口(interface),但我在标题中收到了警告。这是代码:

class GenericSymbolGenerator {
protected: // <== ok
~GenericSymbolGenerator(void) {}

public:
virtual GenericSymbolTableCollection* generateSymbolTableCollection(GenericSymbolTableCollection *gst) = 0;
GenericSymbolGenerator(void) {}
// ~GenericSymbolGenerator(void) {} // <== warning if used
};

class PascalPredefinedSymbolGenerator : public GenericSymbolGenerator {
protected:
~PascalPredefinedSymbolGenerator(void) {} // <== ok

public:
GenericSymbolTableCollection* generateSymbolTableCollection(GenericSymbolTableCollection *pst); // initializes *pst
PascalPredefinedSymbolGenerator(void) {}
// ~PascalPredefinedSymbolGenerator(void) {} <== warning if used
};

class PascalSymbolGenerator : public GenericSymbolGenerator {
protected:
~PascalSymbolGenerator(void) {} // <== ok

public:
GenericSymbolTableCollection* generateSymbolTableCollection(GenericSymbolTableCollection *st); // initializes st
PascalSymbolGenerator(void) {}
// ~PascalSymbolGenerator(void) {} // <== warning if used
};

只要构造函数/析构函数为 void,将析构函数声明为 protected 就没有问题。当类使用堆时就会出现问题(被声明为 protected 析构函数没有办法从“外部”释放类,使对象“坚不可摧”)。 有没有更方便的方法(除了一路公开)?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com