我正在使用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