原创 linux下c++ lesson12 运算符重载基础
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了原创 linux下c++ lesson12 运算符重载基础,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2220字,纯文字阅读大概需要4分钟。
内容图文
![原创 linux下c++ lesson12 运算符重载基础](/upload/InfoBanner/zyjiaocheng/941/8cdd365251e24952965475c06c8e8198.jpg)
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 运算符重载基础全部内容,希望文章能够帮你解决原创 linux下c++ lesson12 运算符重载基础所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。