所以昨天我一直在寻找SO,并找不到以下答案。这种情况来自我正在使用的一些代码,但这里是用于演示它的MCVE。静态演员访问静态const类成员
我在A.h中定义了一个类A,它只有一个静态常量。我已经在头文件中初始化了它。
#ifndef A_H_
#define A_H_
class A {
public:
static const int test = 5;
~A(){};
};
#endif /* A_H_ */
然后我有一个类B需要从类A访问公共静态常量。在这个例子中,它将深度复制值为一个向量。
#ifndef B_H_
#define B_H_
#include "A.h"
#include <vector>
#include <iostream>
class B {
private:
std::vector<int> testVec;
public:
B(){
testVec.push_back((const int)A::test);
//testVec.push_back(static_cast<const int>(A::test)); //Also works
//testVec.push_back(A::test); //Doesn't work without forward declaration of const int A::test in main or in this header
//(Compiler link error: undefined reference to `A::test')
std::cout<< testVec.front() << std::endl;
}
~B(){};
};
#endif /* B_H_ */
然后在主我简单的调用B类的构造函数
#include "B.h"
int main() {
B b;
return 0;
}
//Does the cout from ctor of B and prints 5 to the screen.
我的问题是,为什么一个正常的铸造或静态铸造允许我访问此静态常量变量尚未向前声明。在正常的代码中,我会转发声明该变量或将其声明为extern,因为它已经被定义。什么原因为什么演员让我在没有前向声明的情况下访问这个变量? (这可能看起来像一个简单的问题,可能有一个简单的答案,但我想在这里进一步了解我的知识)。
从编译链接错误输出是:
Invoking: Cygwin C++ Linker
g++ -o "S_Test_p1.exe" ./src/S_Test_p1.o
./src/S_Test_p1.o:S_Test_p1.cpp:(.rdata$.refptr._ZN1A4testE[.refptr._ZN1A4testE]+0x0): undefined reference to `A::test'
collect2: error: ld returned 1 exit status
make: *** [makefile:47: S_Test_p1.exe] Error 1
我这里主要的问题是,为什么铸造的作品,而不是该解决方案是主要还是在波黑定义A ::测试(我知道作品)。我明白这将被接受和正确。主要问题是关于未接受的方式,即铸造。在幕后为什么投射工作链接?
为什么'testVec.push_back(A :: test);'不工作?它应该... – Rene
@Rene,因为静态应该在某处定义并存储在某个地方 –
@Rene它不会链接,我已经用我的嵌入式系统和Cygwin GCC的MULTI编译器试过了。输出:未定义的参考'A :: test' – 9Breaker