static const double in c ++ [英] static const double in c++

查看:491
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆