我正在使用Visual Studio 2008,并且有两个类Parent和Child。 Parent在头文件中声明了一些静态常量变量,然后在cpp文件中定义它们。当我尝试在子类中的switch语句中使用定义作为案例时,我得到以下错误:C2051:案例表达式不是常量。所以我做了一些测试,我看到的行为有些不一致。静态const变量在子类中不是常量
// Parent.h
class Parent
{
public:
Parent();
~Parent(void) { }
static const unsigned long A = 1;
static const unsigned long B;
};
// Parent.cpp
#include "Parent.h"
const unsigned long Parent::B = 2;
Parent::Parent()
{
// Everything works fine here
unsigned long l;
switch(l)
{
case A:
break;
case B:
break;
default:
break;
}
}
// Child.h
#pragma once
#include "Parent.h"
class Child :
public Parent
{
public:
Child(void);
virtual ~Child(void) { }
static const int C = 3;
static const int D;
};
// Child.cpp
#include "Child.h"
const int Child::D = 4;
Child::Child(void)
{
unsigned long l;
switch(l)
{
case A:
break;
case B: // C2051: case expression not constant
break;
case C:
break;
case D:
break;
default:
break;
}
}
我也试过直接指定Parent::B
,这并没有解决问题。除非变量是从父类继承的,否则在所有情况下,为什么表达式都是不变的?
请问,这是什么原因?看起来很奇怪,因为编译时可以知道常量值。 – 2011-03-24 16:07:53
@Antonio:我已经更新了我的回答,试图解释:基本上,这是因为C++源文件是独立编译的。 – 2011-03-24 16:11:48
@Antonio - 如果在编写parent.cpp之前编译child.cpp,则不知道。 – 2011-03-24 16:12:14