大多数C操作容易意图 映射到单个处理器指令当C被发明.当时,取幂不是机器指令,因此是库例程.
根据Bjarne Stroustrup在他的书"C++的设计和演变"中的说法.他们决定避免使用指数运算符,因为:
Python 有**求幂运算符。在 C++ 中,您实际上可以通过一些技巧来定义这样的运算符。通过将一元*运算符与二元*运算符组合起来,如下所示:
#include <cmath>
#include <iostream>
struct Num {
double value;
Num(double value) : value(value) { }
typedef Num* HalfStar;
HalfStar operator*() const { return HalfStar(this); }
Num operator*(const HalfStar& rhs) const
{
return Num(std::pow(value, rhs->value));
}
Num operator*(const Num& rhs) const
{
return Num(value * rhs.value);
}
friend std::ostream& operator<<(std::ostream& os, const Num& n)
{
return os << n.value;
}
};
int main(int argc, char**argv)
{
Num a = 10;
Num b = 9;
std::cout << "a*b = " << (a*b) << "\n";
std::cout << "a**b = " << (a**b) << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但这不适用于非类类型,因此您不能这样做:x**2。
请参阅此处 的实例。
| 归档时间: |
|
| 查看次数: |
36648 次 |
| 最近记录: |