[英]Why would the use of static const in second class give compiler error in first class?
在一個頭文件中,我有2個類聲明。 其中之一包含我想在頂級聲明的類上使用的const值。
以下是基本的實現。
class B;
class A
{
public :
friend class B; // this should not matter since CONST_VAL is public
int a;
A() { a = B::CONST_VAL; } // !!! error line
}
class B
{
public :
static const int CONST_VAL = 1;
}
我覺得這應該是非常基本的概念,但是卻出現編譯器錯誤。 error C2027 : use of undefined type 'B'
以及error 2065: 'CONST_VAL': undeclared identifier
為什么這個構造函數會認為它既不知道B也不知道B :: CONST_VAL?
在您提供的代碼中, B
在文件頂部被向前聲明:
class B;
...
這告訴編譯器B
作為一個類存在 ,但是編譯器對B
一無所知,因為它的定義尚未出現。 使用這樣的前向聲明,使用任何B
對象或成員都沒有意義。 您可以使用B*
指針,因為它們不需要B
任何實現細節。
要解決此問題,您需要在文件頂部或#include
的單獨頭文件中提供B
的定義。 例如:
class B {
public :
static const int CONST_VAL = 1;
};
class A {
public :
int a;
A() : a(B::CONST_VAL) { }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.