本文最后更新于 2026-02-02T00:19:21+08:00

这个幂运算符和我以前发的“逆序成员访问运算符”有异曲同工之妙
在C++中,解引用运算符优先级高于乘法运算符,所以语句 a ** b 本质上是 a * (*b)
- 先对
b 执行解引用
b 解引用的结果和 a 相乘
好了,看过上一篇文章的肯定有思路了
幂运算符
首先,创建一个类 MyInt 用于包装 int 类型(解引用运算符不能作用于基本类型,所以必须用类包装一下基本类型)
1 2 3
| struct MyInt { int value; };
|
然后,重载 MyInt 的解引用运算符,使其返回一个和自身相等的新类
1 2 3 4 5 6 7
| struct MyInt { int value;
MyInt operator*() const noexcept { return MyInt{ value }; } };
|
最后,全局重载乘法运算符
1 2 3
| MyInt operator*(const MyInt& base, const MyInt& exp) noexcept { return MyInt{ static_cast<int>(std::pow(base.value, exp.value)) }; }
|
完整代码:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| #include <cmath> #include <iostream>
struct MyInt { int value;
MyInt operator*() const noexcept { return MyInt{ value }; } };
MyInt operator*(const MyInt& base, const MyInt& exp) noexcept { return MyInt{ static_cast<int>(std::pow(base.value, exp.value)) }; }
std::ostream& operator<<(std::ostream& os, const MyInt& my) { os << my.value; return os; }
int main() { MyInt two{ 2 }, three{ 3 }; MyInt result = two ** three;
std::cout << two << " ** " << three << " = " << result << std::endl; }
|
更好的实现
你可能发现了,将乘法运算符重载为计算幂后会影响正常的乘法
1 2 3 4
| MyInt pow = two ** three;
MyInt multiply = two * three;
|
因此,创建一个额外的类PowProxy显然是更好的实现
MyInt解引用后返回PowProxy
- 添加两个全局乘法重载,一个正常计算乘法,另一个接收
PowProxy计算幂

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| #include <cmath> #include <iostream>
struct PowProxy { int exp; };
struct MyInt { int value;
PowProxy operator*() const noexcept { return PowProxy{ value }; } };
MyInt operator*(const MyInt& base, const PowProxy& pow) noexcept { return MyInt{ static_cast<int>(std::pow(base.value, pow.exp)) }; }
MyInt operator*(const MyInt& a, const MyInt& b) noexcept { return MyInt{ a.value * b.value }; }
std::ostream& operator<<(std::ostream& os, const MyInt& my) { os << my.value; return os; }
int main() { MyInt two{ 2 }, three{ 3 }; MyInt pow = two ** three; MyInt multiply = two * three;
std::cout << two << " ** " << three << " = " << pow << std::endl; std::cout << two << " * " << three << " = " << multiply << std::endl; }
|