#include <iostream>
using namespace std;
#include<vector>
//定义一个类,用于存放数据
class Test
{
int a;
public:
Test(int x) :a(x){}
void print_id()
{
cout << a << endl;
}
void ttt()
{
cout << 111 << endl;
}
void sss()
{
cout << "ssss"<<endl;
}
int GetA()
{
return this->a;
}
};
//定义一个智能指针类,用于托管Test类的指针
class smartpoint
{
Test* p;
public:
smartpoint(Test* x)
{
p = new Test(x->GetA());
}
~smartpoint()
{
if (p != NULL)
{
delete p;
p = NULL;
cout << "析构了" << endl;
}
}
Test* operator->() //重载->运算符,并使用->运算符可以调用返回值的成员函数
{
return this->p;
}
Test& operator*() //重载* 运算符,并使用*运算符获得成员,并通过解引用来调用返回地址所在的对象中的成员,
{
//因为成员是指针类型,重载函数的返回值类型为引用,在获取this指针时要解引用返回对象,而不是返回地址,
return *this->p;
}
};
//重载括号操作符
class Temp_01
{
public:
int operator ()(int x,int y)
{
return x + y;
}
};
class AA
{
public:
AA(){ a = 0; };
AA(int x) :a(x){}
AA operator + (const AA& other) //重载算术操作符 + - * / %同理
{
AA temp;
temp.a = this->a + other.a;
return temp;
}
bool operator ==(const AA& other) //重载关系操作符,> < <= >=同理
{
if (this->a == other.a)
return true;
else
return false;
}
operator double() //重载类型操作符
{
return (double)(this->a);
}
AA& operator<<(int num) //重载输出操作符
{
cout << num << endl;
return *this;
}
AA& operator>>(int& num) //重载输出操作符 传入变量的地址,并由cin输入并返回
{
cin >> num;
return *this;
}
private:
int a;
};
//重载元素操作符
class temp
{
public:
temp(const char* m_buf)
{
buf = new char[strlen(m_buf) + 1];
strcpy(this->buf, m_buf);
}
//重载元素操作符
char& operator [] (int num)
{
return buf[num];
}
~temp()
{
if (buf != NULL)
{
delete buf;
buf = NULL;
}
}
private:
char* buf;
};
int main()
{
AA a(2);
AA b(2);
//算术操作符使用示例
AA c = a + b;
//关系重载操作符使用示例,
if (a == b)
{
cout << "相同" << endl;
}
else
{
cout << "不相同" << endl;
}
//类型重载操作符使用示例
double reslut = (double)c; //调用类型操作符,并将变量类型转换
//元素操作符操作示例
temp temp1("helloworld");
temp1[0] = 'R'; //调用元素操作符重载,并修改指定位置的元素
//重载元素操作符
int num_1;
//重载输入输出操作符
c >> num_1; //调用输入重载操作符
c << num_1; //调用输出重载操作符
//重载括号()运算符
Temp_01 temp11;
int s =temp11(1, 4);
smartpoint sp(new Test(1));
//使用重载->操作符
sp->print_id();
sp->sss();
sp->ttt();
//使用重载*操作符
(*sp).print_id();
(*sp).sss();
(*sp).ttt();
return 0;
}