正如标题所说。以下人为设计的示例似乎适用于键盘:http://codepad.org/4cgGmvDQ在我的 Linux 机器上的 GCC 4.1.2 下。
#include<stdlib.h>
#include<new>
class IBase
{
public:
virtual ~IBase(){}
};
class B : public IBase
{
public:
virtual ~B(){}
};
class D : public B
{
public:
virtual ~D(){ }
};
int main()
{
void* p = malloc(sizeof(D));
D* d = new(p) D();
B* b = static_cast<B*>(d);
b->~IBase();
free(p);
}
但是 Visual Studio Pro 2012 11.0.61030.00 Update 4 失败了:
main.cpp(30): error C2300: 'B': 类没有名为 '~IBase' 的析构函数
显然,可以很容易地重新编写示例来避免该问题,但我的实际代码库没有提供任何其他选项。有人熟悉 Microsoft 编译器的这个特殊故障吗?
最佳答案
这不是 MSVC 中的错误。根据标准,§3.4.5 [basic.lookup.classref]/p2-3(引用 N3936,强调我的):
If the id-expression in a class member access (5.2.5) is an unqualified-id, [...]
If the unqualified-id is
~type-name
, the type-name is looked up in the context of the entire postfix-expression. If the typeT
of the object expression is of a class typeC
, the type-name is also looked up in the scope of classC
. At least one of the lookups shall find a name that refers to (possibly cv-qualified)T
.
在您的代码中,T
是B
,查找IBase
显然找不到引用B 的名称
。因此,您的代码格式错误。如果 g++ 接受它,它要么是错误要么是扩展。
因为听起来 B
代表的实际类型在您的真实代码中是“不可描述的”,但是 IBase
可以编写,最简单的解决方案就是简单地转换b
到 IBase *
。
关于c++ - 在派生指针上显式调用基类析构函数时编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25376209/