C ++中的运算符重载示例

时间:2013-10-19 02:14:58

标签: c++

我需要一个简单的运算符重载示例。不使用类或结构。在这里,我试过但得到错误:

#include <iostream.h>
int operator+(int a, int b)
{
  return a-b;
}

void main()
{
  int a,b,sum;
  cin>>a>>b;
  sum=a+b;  //Actually it will subtruct because of + operator overloading.
  cout<<"Sum of "<<a<<" & "<<b<<"(using overloading)"<<sum;
}

我收到以下错误:

Compiling OVERLOAD.CPP:
Error OVERLOAD.CPP 3: 'operator +(int,int)' must be a member function or have a parameter of class type

让我知道是否有可能重载运算符(sum = a + b)?如果是,那么请在我的来源中进行更正。

3 个答案:

答案 0 :(得分:8)

无法覆盖像int这样的基本类型的运算符。正如编译器所述,至少有一个参数的类型必须是一个类。

答案 1 :(得分:3)

运算符重载仅适用于类类型。原始类型运算符不是由函数定义的。有关详细信息,请参阅this question

如果您有类类型,则可以重载运算符:

class A
{
    int _num;

public:
    A(int n) : _num(n) {}

    int operator+(const int b) const
    {
        return _num + b;
    }
}

int main()
{
    A a(2);
    int result = a + 4; // result = 6

    return 0;
}

答案 2 :(得分:2)

如果两个操作数都是基本类型,则无法覆盖运算符。编译器说至少一个操作数应该是一个类的对象。

class Demo{
   int n;
   Demo(int n){
      this.n = n;
   }
   int operator+(int a){
    return n + a;
   }
}


int main(){  
   Demo d(10);
   int result = d + 10; //See one operand is Object
   return 0;
}

当您使用类成员函数进行运算符重载时,至少第一个操作数应该是对象。你做不到10 - d。为此,您需要使用friend函数实现运算符重载。

  friend int operator-(int a, Demo d){
    return a - n;
  }