运算符重载
来源:互联网 发布:淘宝卖家销量排行榜 编辑:程序博客网 时间:2024/06/11 10:29
1.运算符
C++预定义表示对数据的运算,如+,-,*,/,%,^,&,~,|,!,=,<<,>>,!=等等。只能用于基本的数据类型(整形、实型、字符型、逻辑型等)
2.自定义数据类型与运算符重载
C++提供了数据抽象的手段:用户自己定义数据类型(类)而类的成员函数-》操作对象很不方便
运算符重载:对抽象数据类型也能够直接使用C++提供的运算符:程序更简洁,代码更容易理解
对已有的运算符赋予多重的含义;使同一运算符作用于不同数据类型时-》不同类型的行为
目的:扩展C++中提供的运算符的适用范围,以用于类所表示的抽象类型
eg.
(5,10i)+(4,8i)=(9,18i);5+4=9;
3.运算符重载
运算符重载的实质是函数重载返回值类型 operator运算符 (形参表)
{
……
}
4.运算符重载为普通函数
#include <iostream>#include <string>using namespace std;class Complex {public:Complex(double r = 0.0, double i = 0.0) { //构造函数real = r; //初始化实部虚部imaginary = i;}double real; //定义两个成员变量double imaginary;};Complex operator+(const Complex &a, const Complex &b) //重载函数{return Complex(a.real+b.real,a.imaginary+b.imaginary);}//类名(参数表)就代表一个对象void main(){Complex a(1, 2), b(2, 3), c;c = a + b;//相当于 operator+(a,b)cout << "When a(1,2)+b(2,3)" << endl;cout << "The real is:"<<c.real<<"\nThe imaginary is:"<<c.imaginary << endl;}
5.运算符重载为成员函数
#include <iostream>#include <string>using namespace std;class Complex {public:Complex(double r = 0.0, double m = 0.0):real(r),imaginary(m){} //constructorComplex operator+ (const Complex &); //additionComplex operator- (const Complex &); //subtraction//private:double real; //定义两个成员变量double imaginary;};//Overloaded addition operatorComplex Complex::operator+(const Complex & operand2){return Complex(real+operand2.real,imaginary+operand2.imaginary);}//Overloaded subtraction operatorComplex Complex::operator-(const Complex & operand2){return Complex(real-operand2.real,imaginary-operand2.imaginary);}int main(){Complex a(1.5, 2.8), b(2.3, 3.7), c,d;c = a + b;// x=y.operator+(z)d = a - b;// x=y.operator-(z)cout << c.real << "\t" << c.imaginary << endl;cout << d.real << "\t" << d.imaginary << endl;return 0;}
阅读全文
0 0
- 运算符重载 [++,--,+,<<; &&,||(不可重载)]
- 重载之运算符重载
- 重载赋值运算符
- C++运算符重载
- 运算符重载
- 运算符重载总结
- 运算符重载例子
- 运算符重载
- 运算符重载
- 基础:运算符重载
- 运算符重载
- 运算符重载
- 重载赋值运算符
- C#运算符重载
- C++-运算符重载
- 重载赋值运算符
- 运算符重载
- 有关运算符重载
- JavaScript中5个常见的陷阱
- SpringMVC入门,配置过程
- HTTP Status 500
- mybatis中sql语句遇到大于号或小于号
- 利用css内置规则@font-face加载特殊字体
- 运算符重载
- c语言fread函数的总结
- 【C#学习】.NET类库中的继承
- Maven 插件之 docker-maven-plugin 的使用
- centos6.5 MailScanner+ Spamassassin垃圾邮件过滤器+clamav 杀毒软件
- HDU
- [Python] wxPython 菜单栏控件学习总结(原创)
- JPush极光推送Java服务器端实例
- 等待唤醒机制