当问题在性质上完全不同时,为什么要使用 C2259?

Why a C2259 when the problem is utterly different in nature?

本文关键字:为什么 C2259 问题 性质上      更新时间:2023-10-16

尝试编译下面的代码片段时,我得到了错误:

error C2259: 'cTest': cannot instantiate abstract class
note: due to the following members:
note: void iTest::log(iTest::eLevel): is abstract
note: see declaration of 'iTest::log'

抽象成员函数已使用相同的签名定义。

删除第二个枚举可以解决问题,无论如何它都不是故意的。

但是我仍然不知道为什么给出 C2259,我只能发现应该定义成员来修复。

class iTest
{
public:
enum eLevel
{
Info,
};
virtual void foo( eLevel l ) = 0;
};
class cTest : public iTest
{
public:
enum eLevel
{
Info,
};
virtual void foo( eLevel l )
{
}
};
int main()
{
iTest* t = new cTest();
}

您收到此错误的原因是iTest::foocTest::foo的第二个定义没有相同的签名,因此ctest没有实现iTest::foo

使用全名,您的声明如下:

class iTest
{
public:
enum eLevel
{
Info,
};
virtual void foo( iTest::eLevel l ) = 0;
};
class cTest : public iTest
{
public:
enum eLevel
{
Info,
};
virtual void foo( cTest::eLevel l )
{
}
};

可以看出,foo(iTest::eLevel)foo(cTest::eLevel)不同,因此cTest仍然是一个抽象类,不能实例化。

您可以完全删除cTest::eLevel,也可以cTest::foo声明为

class cTest : public iTest
{
public:
enum eLevel
{
Info,
};
virtual void foo( iTest::eLevel l )
{
}
};