操作符重载
来源:互联网 发布:java考勤管理系统源码 编辑:程序博客网 时间:2024/04/28 10:20
操作符重载本质也就是函数调用而已!
#include <cstdlib>
#include <iostream>
using namespace std;
struct Complex
{
int a;//实部
int b;//虚部
};
/*
Complex add(Complex c1,Complex c2)
{
Complex c;
c.a=c1.a+c2.a;
c.b=c1.b+c2.b;
return c;
}
*/
Complex operator+(Complex c1,Complex c2)
{
Complex c;
c.a=c1.a+c2.a;
c.b=c1.b+c2.b;
return c;
}
int main(int argc, char *argv[])
{
Complex c1{1,2};
Complex c2{1,2};
//Complex c=operator+(c1,c2);
Complex c=c1+c2;
cout<<"c.a = "<<c.a<<endl;
cout<<"c.b = "<<c.b<<endl;
cout << "Press the enter key to continue ...";
cin.get();
return EXIT_SUCCESS;
}
类的操作符重载
#include <cstdlib>
#include <iostream>
using namespace std;
class Complex
{
private:
int a;
int b;
public:
Complex(int a=0,int b=0)
{
this->a=a;
this->b=b;
}
friend Complex operator+(const Complex& c1,const Complex& c2);
friend ostream& operator<<(ostream& out,const Complex& c);
};
//重载“+ ”
Complex operator+(const Complex& c1,const Complex& c2)
{
Complex c;
c.a=c1.a+c2.a;
c.b=c1.b+c2.b;
return c;
}
//重载 "<<"
ostream& operator<<(ostream& out,const Complex& c)
{
out<<c.a<<"+"<<c.b<<"i";
return out;
}
int main(int argc, char *argv[])
{
Complex c1(1,2);
Complex c2(3,4);
Complex c=c1+c2; //operator+(c1,c2)
cout<<c<<endl;
cout << "Press the enter key to continue ...";
cin.get();
return EXIT_SUCCESS;
}
友元
可以访问private成员
成员函数重载只是需要右值作为操作数即可,因为默认左值是this指针
#include <cstdlib>
#include <iostream>
using namespace std;
class Complex
{
private:
int a;
int b;
public:
Complex(int a=0,int b=0)
{
this->a=a;
this->b=b;
}
Complex operator+(const Complex& c);
friend ostream& operator<<(ostream& out,const Complex& c);
};
//重载“+ ”
Complex Complex::operator+(const Complex& c2)
{
Complex c;
c.a=a+c2.a;
c.b=b+c2.b;
return c;
}
//重载 "<<"
ostream& operator<<(ostream& out,const Complex& c)
{
out<<c.a<<"+"<<c.b<<"i";
return out;
}
int main(int argc, char *argv[])
{
Complex c1(1,2);
Complex c2(3,4);
Complex c=c1+c2; //--》 Complex c=c1.operator+(c2);
cout<<c<<endl;
cout << "Press the enter key to continue ...";
cin.get();
return EXIT_SUCCESS;
}
成员函数重载操作符比全局操作符重载少一个参数
当无法修改左操作数时只能使用全局函数进行重载
=,[],()和->操作符只能通过成员函数进行重载
0 0
- c++重载操作符
- C++ 操作符重载
- 操作符重载浅析
- 操作符重载
- 10.8 操作符重载
- 操作符重载
- 操作符重载手册
- C#操作符重载
- 操作符重载手册
- 操作符重载手册
- 六操作符重载
- 操作符的重载
- C#操作符重载
- 多态,操作符重载
- 操作符重载集锦
- 重载操作符
- 操作符重载
- 操作符重载手册
- 最小生成树模板(prim前向星)
- Maven学习笔记第二节(pom文件)
- 医学图像处理笔记(2)
- 方法调用与带标签的continue和break
- 关于从list或者数组中随机抽取部分不重复元素的问题探究
- 操作符重载
- 使用PackageManager来获取应用信息
- 使用 TouchDelegate 扩大控件的点击范围
- shell 之 进程前后台切换
- hibernate查询异常:No Dialect mapping for JDBC type:-9(sql server)
- 驱动模板
- Android中View中的scrollTo(),scrollBy(),getScrollX(), getScrollY()详解
- Matlab Language Index
- Linux学习笔记13