Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
157 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...