成员函数
#include <iostream>
using namespace std;
class B
{
private:
int c;
public:
B(){}
B(int x)
{
c=x;
}
B operator-(B &b)
{
B s;
B a=*this;
s.c=a.c-b.c;
return s;
}
B operator-()
{
this->c=-(this->c);/用this比较好理解一点
return *this;
}
void show()
{
cout<<c<<endl;
}
};
int main()
{
B a(5),b(2);
a=-a;
a.show();
(a-b).show();
}
友元函数
#include <iostream>
using namespace std;
class B
{
private:
int c;
public:
B(){}
B(int x)
{
c=x;
}
friend B operator-(B &a);
friend B operator-(B &a,B &b);
void show()
{
cout<<c<<endl;
}
};
B operator-(B &a)
{
a.c=-a.c;
return a;
}
B operator-(B &a,B &b)
{
B s;
s.c=a.c-b.c;
return s;
}
int main()
{
B a(5),b(2);
a=-a;
a.show();
(a-b).show();
}