问题描述
我正在创建一个库,该库的概念类似于python。
C没有像python( **
)这样的幂运算符(例如 pow(x,n)
等价于python中的 x ** n
。
I'm creating a library which will have concepts similar kind of python.C doesn't have any power operator like python has (**
) (e.g. pow(x,n)
is equivalent to x**n
in python).
我尝试使用预处理程序指令。
I tried to solve this problem using a Pre-Processor directive. but didn't find any trick.
因为^该运算符用于XOR运算,所以我认为它不能用于幂运算符(可以吗?)
Since ^ this operator is for XOR operation so I think it cannot be used for power operator(can we?)
所以替代解决方案是双星( **
),因为 **
是编译器无法识别的运算符,因此我们如何使编译器知道它。
so alternative solution is double star(**
) because **
is unrecognized operator to compiler so how can we make this known to compiler.
对此的建议方法或解决方案。
suggest approach or solution for this.
推荐答案
您无法在C ++中添加新的运算符,因此无法使用 **
(或其他一些新功能)。另外,当双方都是内置类型时,您不能重载运算符,因此使用现有的运算符(例如 ^
)来实现将浮点数/整数提高为浮点数/整数的幂也出来了。请参阅(如下面的评论中所述。)
You cannot add new operators to C++, so using **
(or some other new thing) is out. Also, you cannot overload operators when both sides are built-in types, therefore using an existing operator (e.g. ^
) to implement raising floats/ints to powers that are floats/ints is also out. See this question on Stroustrup's C++ FAQ (as mentioned in the comments below.)
您可以实现自己的数值类并重载所需的任何运算符,但这并不容易,而且不会像优雅或酷一样如您所想。
You can implement you own numeric class and overload any operator you want for it, but it won't be easy and it won't be as "elegant" or as cool as you seem to think.
因此,只需使用一个函数即可。
So, just use a function.
这篇关于C语言中的电力运营商程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!