C++ 重载关系操作符
2024-09-04 23:36:08
#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 << << 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 = ; };
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) + ];
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();
AA b();
//算术操作符使用示例
AA c = a + b; //关系重载操作符使用示例,
if (a == b)
{
cout << "相同" << endl;
}
else
{
cout << "不相同" << endl;
}
//类型重载操作符使用示例
double reslut = (double)c; //调用类型操作符,并将变量类型转换 //元素操作符操作示例
temp temp1("helloworld");
temp1[] = 'R'; //调用元素操作符重载,并修改指定位置的元素
//重载元素操作符
int num_1; //重载输入输出操作符
c >> num_1; //调用输入重载操作符
c << num_1; //调用输出重载操作符 //重载括号()运算符
Temp_01 temp11;
int s =temp11(, ); smartpoint sp(new Test());
//使用重载->操作符
sp->print_id();
sp->sss();
sp->ttt();
//使用重载*操作符
(*sp).print_id();
(*sp).sss();
(*sp).ttt();
return ;
}
最新文章
- IRLS(迭代加权最小二乘)
- PowerDesigner 学习笔记
- REPL LOG
- c语言的几个重要知识点
- C#中的interface、virtual和abstract
- (转)解析php中die(),exit(),return的区别
- ";ORA-00942: 表或视图不存在 ";的原因和解决方法[转]
- 字典:当索引不好用时2 - 零基础入门学习Python026
- 关于chrome浏览器更新后快捷工具失效的解决方法
- iOS推送介绍
- Net平台下的消息队列介绍
- HTML 头标签的 <;title>; <;base>; <;meta>; <;link>; <;script>; 的内容意思
- Kibana(一张图片胜过千万行日志)
- EOJ Monthly 2019.2
- latex 希腊字母表示
- Max Factor 2710 最大的合数的质数因子
- WC、KOI2017小随想..
- C/C++三目运算符
- 切换用户身份su与sudo
- vue 实战 遇到问题记录