注册 登录
编程论坛 C++教室

运算符重载参数问题

pengshenhu 发布于 2012-06-29 10:37, 435 次点击
我想重载“^”符来实现一个数求n次方,这是我的代码:
#include <iostream>
using namespace std;
double operator ^(double &a,int &exp)//exp为指数
{
    int i=1;
    double sum=a;
    for(i;i<exp;i++)
    {
        sum=sum*a;//求a的exp次方
    }
    return sum;
}

void main()
{
    double a=2;
    double b=0;
    b=a^2;
    cout<<b<<endl;
}
错误如下:
error C2803: 'operator ^' must have at least one formal parameter of class type
error C2296: '^' : illegal, left operand has type 'double'
请大神帮忙解释下
3 回复
#2
rjsp2012-06-29 10:45
只有自定义的类才可以重载操作符
否则就改变了原本的语义

#3
pengshenhu2012-06-29 10:47
回复 2楼 rjsp
那就是说运算符重载的参数只能是类的类型咯?
#4
lxqlyld2012-06-29 13:25
我用的是C++ Builder 6.0编译后有三个错误:
只有本站会员才能查看附件,请 登录

分别为:1、double operator ^(double &a,int &exp)必须是一个成员函数或有一个类型参数;2、 b=a^2;是一个非法的浮点运算;3、“a”是一个有符号数,不能使用
1