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/C++编程中const的使用详解 2023-03-26
- 详解c# Emit技术 2023-03-25
- C利用语言实现数据结构之队列 2022-11-22
- C++使用easyX库实现三星环绕效果流程详解 2023-06-26
- C语言基础全局变量与局部变量教程详解 2022-12-31
- 一文带你了解C++中的字符替换方法 2023-07-20
- C++详细实现完整图书管理功能 2023-04-04
- C++中的atoi 函数简介 2023-01-05
- 如何C++使用模板特化功能 2023-03-05
- C语言 structural body结构体详解用法 2022-12-06