static const double in c ++ [英] static const double in c++
问题描述
这是使用静态const变量的正确方法吗?在我的顶层类(Shape)
Is this the proper way to use a static const variable? In my top level class (Shape)
#ifndef SHAPE_H
#define SHAPE_H
class Shape
{
public:
static const double pi;
private:
double originX;
double originY;
};
const double Shape::pi = 3.14159265;
#endif
然后在一个扩展Shape的类中,使用Shape :: pi。我得到一个链接器错误。我把const double Shape :: pi = 3.14 ...移动到Shape.cpp文件,然后我的程序编译。为什么会这样呢?由于 const double Shape :: pi = 3.14159265;
And then later in a class that extends Shape, I use Shape::pi. I get a linker error. I moved the const double Shape::pi = 3.14... to the Shape.cpp file and my program then compiles. Why does that happen? thanks.
推荐答案
是 Shape :: pi
的定义,C ++只允许一个符号的单个定义(称为 one-definition-rule ,您可能会看到它的缩写形式ODR)。当定义在头文件中时,每个翻译单元得到它自己的定义,打破了该规则。
Because const double Shape::pi = 3.14159265;
is the definition of Shape::pi
and C++ only allows a single definition of a symbol (called the one-definition-rule which you may see in it's acronym form ODR). When the definition is in the header file, each translation unit gets it's own definition which breaks that rule.
通过将其移动到源文件中, 。
By moving it into the source file, you get only a single definition.
这篇关于static const double in c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!