-1

I'm trying to create a class of complex number and want to create the imaginary unit i as constant. 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. But when I write the code on the top in main.cpp , I get undeclared variable error.

How can I do this?

Note : I've defined the = and * operators

4

2 回答 2

2

extern const complex icomplex.h中声明。

如果您不声明它i必须extern在使用它的每个编译单元中定义。链接两个这样的编译单元将产生重复定义错误。

于 2013-03-21T17:29:48.647 回答
0

您声明complex::i但您正在尝试使用i. 将您的代码更改为

complex c = 2 * complex::i;

或者创建一个全局常量i(注意:这不是一个好主意;但您可以在 namspace 中执行此操作)。

于 2013-03-21T17:29:52.947 回答