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

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

c++ - Program of power operator in C

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...