1-运算符重载概念.cpp#include iostreamusing namespace std;class Complex{//friend Complex operator+(const Complex c1, const Complex c2);private:int a; //实部int b; //虚部public:Complex(int...
1-运算符重载概念.cpp
#include <iostream>
using namespace std;
class Complex
{
//friend Complex operator+(const Complex &c1, const Complex &c2);
private:
int a; //实部
int b; //虚部
public:
Complex(int _a, int _b)
{
this->a = _a;
this->b = _b;
}
void print()
{
cout << a << " + " << b << "i" << endl;
}
Complex operator+(const Complex &c)
{
Complex t(0, 0);
t.a = this->a + c.a;
t.b = this->b + c.b;
return t;
}
};
//运算符重载本质就是函数的重载
/*Complex operator+(const Complex &c1, const Complex &c2)
{
Complex t(0, 0);
t.a = c1.a + c2.a;
t.b = c1.b + c2.b;
return t;
}*/
int main()
{
Complex c1(1, 2);
Complex c2(2, 3);
c1.print();
//c1 + c2;
Complex t(0, 0);
//t = operator+(c1, c2);
t = c1 + c2; //编译器会转换成 t = c1.operator+(c2)
t.print();
return 0;
}
2-重载输出运算符.cpp
#include <iostream>
using namespace std;
class Complex
{
//friend Complex operator+(const Complex &c1, const Complex &c2);
friend ostream &operator<<(ostream &out, const Complex &c);
private:
int a; //实部
int b; //虚部
public:
Complex(int _a, int _b)
{
this->a = _a;
this->b = _b;
}
void print()
{
cout << a << " + " << b << "i" << endl;
}
/*ostream &operator<<(ostream &out) //如果左操作数不能修改,则不能重载成成员函数
{
out << this->a << " + " << b << "i";
return out;
}*/
};
//运算符重载本质就是函数的重载
/*Complex operator+(const Complex &c1, const Complex &c2)
{
Complex t(0, 0);
t.a = c1.a + c2.a;
t.b = c1.b + c2.b;
return t;
}*/
ostream &operator<<(ostream &out, const Complex &c)
{
out << c.a << " + " << c.b << "i";
return out;
}
int main()
{
Complex c1(1, 2);
c1.print();
cout << c1 << endl; //operator<<(operator<<(cout, c1), endl); 等价于 cout.operator<<(c1)
return 0;
}
3-单目运算符重载.cpp
#include <iostream>
using namespace std;
class Complex
{
friend ostream &operator<<(ostream &out, const Complex &c);
private:
int a; //实部
int b; //虚部
public:
Complex(int _a, int _b)
{
this->a = _a;
this->b = _b;
}
//后置++
Complex operator++(int) //通过占位参数来构成函数重载
{
Complex t = *this;
this->a++;
this->b++;
return t;
}
//前置++
Complex &operator++()
{
this->a++;
this->b++;
return *this;
}
};
ostream &operator<<(ostream &out, const Complex &c)
{
out << c.a << " + " << c.b << "i";
return out;
}
int main()
{
Complex c1(1, 2);
cout << c1++ << endl;
cout << ++c1 << endl;
return 0;
}
沃梦达教程
本文标题为:原创 linux下c++ lesson12 运算符重载基础
猜你喜欢
- C语言qsort()函数的使用方法详解 2023-04-26
- C语言详解float类型在内存中的存储方式 2023-03-27
- Qt计时器使用方法详解 2023-05-30
- C语言手把手带你掌握带头双向循环链表 2023-04-03
- 详解C语言中sizeof如何在自定义函数中正常工作 2023-04-09
- Easyx实现扫雷游戏 2023-02-06
- C++ 数据结构超详细讲解顺序表 2023-03-25
- ubuntu下C/C++获取剩余内存 2023-09-18
- 我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上? 2022-10-30
- c++ const 成员函数,返回一个 const 指针.但是返回的指针是什么类型的 const? 2022-10-11