Kac*_*iej 3 c++ compiler-errors operator-overloading operators
我写了,我经常使用的应用程序pow功能的math.h库.我试图超载operator^以使取幂更容易和更快.我写了这段代码:
#include <iostream>
#include <math.h>
using namespace std;
int operator^(int, int); // line 6
int main(int argc, char * argv[]) { /* ... */ }
int operator^(int a, int n) // line 21
{
return pow(a,n);
}
Run Code Online (Sandbox Code Playgroud)
编译器(我在Linux上使用g ++)给我这些错误:
main.cpp:6:23:错误:'int operator ^(int,int)'必须有一个类的参数或枚举类型main.cpp:21:27:error:'int operator ^(int,int)'必须有一个类或枚举类型的参数
我试图重载operator ^以使取幂更容易和更快
你拼错了混乱,因为它肯定不是更快,也不容易.如果你这样做,任何维护你代码的人都会讨厌你.
幸运的是,C++至少需要一个参数是用户定义的类型,所以你不能这样做.