[英]How to create global constant of a class - C++
I'm trying to create a class of complex number and want to create the imaginary unit i as constant. 我正在尝试创建一类复数,并希望将虚数单位i创建为常量。 I want to be able to use it in any code when the class is included.
当包含该类时,我希望能够在任何代码中使用它。 For example :
例如 :
#include "complex.h"
complex c = 2*i;
I've tried to define it that way : static const complex i
in complex.h under public:
and const complex complex::i = complex(0,1)
in complex.cpp. 我试图用这种方式定义它:
public:
。下的complex.h中的static const complex i
,而complex.cpp中的const complex complex::i = complex(0,1)
。 But when I write the code on the top in main.cpp , I get undeclared variable error. 但是,当我在main.cpp的顶部编写代码时,出现未声明的变量错误。
How can I do this? 我怎样才能做到这一点?
Note : I've defined the =
and *
operators 注意 :我已经定义了
=
和*
运算符
Declare extern const complex i
in complex.h . 在complex.h中声明
extern const complex i
。
If you do not declare i
to be extern
it must be defined in every compilation unit that uses it. 如果不声明
i
为extern
则必须在使用它的每个编译单元中对其进行定义。 Linking two such compilation units will then produce a duplicate definition error. 链接两个这样的编译单元将产生重复的定义错误。
You declared complex::i
but you are trying to use i
. 您声明了
complex::i
但您尝试使用i
。 Either change your code to 将您的代码更改为
complex c = 2 * complex::i;
Or create a global constant i
(note: that's not a good idea; but you might do it inside a namspace). 或创建一个全局常数
i
(注意:这不是一个好主意;但是您可以在namspace中执行此操作)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.