#include <iostream>
#include <stdlib.h>
using namespace std;
class Point
{
int x;
int y;
//friend Point operator + (Point& a,Point& b);
friend ostream& operator << (ostream& os,Point& p);
friend istream& operator >> (istream& is,Point& p);
public:
//无参构造函数 使用初始化列表进行初始化
Point( int x = 0, int y = 0 ):x(x),y(y)
{
cout << this << endl;
}
//拷贝构造函数
Point(Point& that)
{
x = that.x;
y = that.y;
}
void show(void)
{
cout << "x = " << x << "," << " y = " << y << endl;
}
~Point(void)
{
cout << this << endl;
cout << "------析构函数------" << endl;
}
//成员函数 重载
// a + b a - b
Point operator + (Point& a)
{
Point t(this->x + a.x,this->y + a.y);
//t.show(); return ;此种方式不返回 但是会返回一个随机的 因为有返回值
return t;
}
// a * b a / b
Point operator * (Point& a)
{
Point t(this->x * a.x,this->y * a.y);
return t;
}
// a += b a -= b
Point& operator += (Point& a)
{
this->x += a.x;
this->y += a.y;
return *this;
}
// 前++ --
Point& operator ++(void)
{
this->x++;
this->y++;
return *this;
}
// 后++ --
Point operator ++(int)
{
Point t(*this);
this->x++;
this->y++;
return t;
}
// []下标运算符
Point& operator [](int i)
{
x += i;
y += i;
return *this;
}
// ()函数运算符
Point& operator () (int x,int y)
{
this->x += x;
this->y += y;
return *this;
}
// ->
Point* operator -> (void)
{
return this;
}
// new会自动调用重载的new函数再构造函数
void* operator new (unsigned int size)
{
cout << "---------new-----------" << endl;
return malloc(size);
}
// delete会先调用析构再调用重载的delete函数
void operator delete (void* p)
{
cout << "--------delete---------" << endl;
free(p);
}
void operator = (Student& that)
{
if(this == &that) return;
// 释放旧资源
delete[] name;
// 申请新资源
name = new char[strlen(that.name)+1];
// 拷贝新内容
strcpy(name,that.name);
sex = that.sex;
age = that.age;
}
};
/*
Point operator + (Point& a,Point& b)
{
Point t(a.x+b.x,a.y+b.y);
return t;
}*/
// 输入、输出运算符不能重载为成员函数,只能是友元
ostream& operator << (ostream& os,Point& p)
{
return os << "x=" << p.x << "," << "y=" << p.y << " "<< &p;
}
istream& operator >> (istream& is, Point& p)
{
cout << "x = " ;
is >> p.x;
cout << "y = ";
is >> p.y ;
return is;
}
int main(int argc, char const *argv[])
{
Point a(1,1);
Point b(2,2);
(a+b).show();
(a*b).show();
(a++).show();
cout << a << endl;
cout << a(1,1) << endl;
cout << a[-1] << endl;
cout << ++b << endl;
cin >> a;
a.show();
return 0;
}
c++ 重载运算符的详细使用例子
最新推荐文章于 2022-11-05 10:51:59 发布