poo*_*rva 9 c++ operator-overloading operators
如何定义运算符**,使其可以执行2个数的取幂.例如2 ** 3.应该给出答案为8.
或间接有任何方法我可以用运算符重载而不是#define宏来做到这一点?
你不能.您只能在C++中重载现有的运算符; 你不能添加新的,或改变现有运营商的arity或关联性.甚至预处理器在这里也是无能为力的 - 它的标识符不能是符号.
如果你愿意做出妥协**并且觉得你的代码混淆:
#include <cmath>
#include <iostream>
struct foo {
foo(int i) : i_(i) {}
int operator*(int exp)
{
return std::pow(i_,exp);
}
private:
int i_;
};
struct bar {
} power_of;
foo operator*(int i, bar)
{
return foo{i};
}
int main()
{
std::cout << 2 *power_of* 3; // prints 8
}
Run Code Online (Sandbox Code Playgroud)
否则,只需使用std::pow.
与其他注释一样,这对于内置类型是不可能的,但是你可以让它适用于这样的自定义类型(最小代码示例):
#include <cmath>
#include <iostream>
struct dummy;
struct Int
{
int i;
Int() : i(0) {}
Int(const int& i) : i(i) {}
dummy operator*();
};
struct dummy
{
Int* p;
dummy(Int* const p) : p(p) {}
int& operator*()
{
return p->i;
}
};
dummy Int::operator*()
{
return dummy(this);
}
int operator*(const Int& lhs, const dummy& rhs)
{
return std::pow(lhs.i, rhs.p->i);
}
int main()
{
Int a(2);
Int b(2);
std::cout<< a ** b << std::endl;
}
Run Code Online (Sandbox Code Playgroud)