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

C++ C+中的运算符重载示例+;,c++,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. cou

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

#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)?如果是,请在我的源代码中进行更正。

不可能覆盖基本类型(如int)上的运算符。如编译器所述,至少有一个参数的类型必须是类。

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

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

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;
}

如果两个操作数都是基元类型,则无法重写运算符。编译器指示至少一个操作数应该是类的对象

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;
}
使用类成员函数执行运算符重载时,至少第一个操作数应该是object。您不能执行
10-d
。为此,您需要使用
friend
函数实现运算符重载

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

另外,是否要重载“+”do(a-b)?为
int
创建一个包装类,并重载该包装类的运算符。KtoDISO给出了一个例子。<代码>空main < /C> >不是合法C++。使用
intmain
“当您使用普通函数进行运算符重载时”,我想您指的是“成员函数”或“实例方法”;另外,通常不需要
friend
,您需要的术语是“自由功能”。