c++运算符重载基础知识详解

Orenda ·
更新时间:2024-09-20
· 574 次阅读

实际上,很多C++运算符已经被重载。eg:将*运算符用于地址,将得到存储在这个地址中的值,将他用于2个数字时,得到的将是他们的乘积。C++根据操作数的数目和类型来决定采用哪种操作。

C++允许将运算符重载扩展到用户定义的类型。例如,允许使用+将两个对象相加。编译器将根据操作数的数目和类型决定使用加法定义。运算符重载可以使代码看起来更自然。例如,将2个数组相加是一种常见的运算。通常,需要使用下面这样的for循环来实现:
代码如下:
for (int i = 0; i < 20; i++)
evening[i] = sam[i] + janet[i]; // add element by element

但在C++中,可以定义一个表示数组的类,并重载+运算符,于是便有这样的语句:

total = arr1+arr2;
一个计算时间的例子
mytime.h

代码如下:
#include"stdafx.h"
#include"MyTime.h"
#include<iostream>

int_tmain(intargc,_TCHAR*argv[])
{
//比导入整个名称空间更经济
usingstd::cout;
usingstd::endl;

Timeplanning;
Timecoding(2,50);
Timefixing(5,55);
Timetotal;
cout<<"planningtime=";
planning.Show();
cout<<endl;
cout<<"codingtime=";
coding.Show();
cout<<endl;
cout<<"fixingtime=";
fixing.Show();
cout<<endl;
total=coding.Sum(fixing);
cout<<"coding.Sum(fixing)=";
total.Show();
cout<<endl;
total=coding+fixing;
cout<<"coding+fixing=";
total.Show();
cout<<endl;
getchar();
return0;
}

调用

代码如下:
#include"stdafx.h"
#include"MyTime.h"
#include<iostream>

int_tmain(intargc,_TCHAR*argv[])
{
//比导入整个名称空间更经济
usingstd::cout;
usingstd::endl;

Timeplanning;
Timecoding(2,50);
Timefixing(5,55);
Timetotal;
cout<<"planningtime=";
planning.Show();
cout<<endl;
cout<<"codingtime=";
coding.Show();
cout<<endl;
cout<<"fixingtime=";
fixing.Show();
cout<<endl;
total=coding.Sum(fixing);
cout<<"coding.Sum(fixing)=";
total.Show();
cout<<endl;
total=coding+fixing;
cout<<"coding+fixing=";
total.Show();
cout<<endl;
getchar();
return0;
}

执行结果

重点讲解
1.sum函数中将参数声明为引用,可以提高运行效率,节省内存

2.sum函数中,返回值不能是引用。因为sum对象是局部变量,在函数结束时将被删除,因此引用将指向一个不存在的对象。使用返回类型Time意味着在删除sum之前构造他的拷贝,调用函数将得到他的拷贝。

您可能感兴趣的文章:C++ 开发之实现操作符重载的实例C++ 中重载和运算符重载加号实现矩阵相加实例代码深入解析C++编程中的运算符重载详解C++编程中的单目运算符重载与双目运算符重载C++运算符重载的方法详细解析C++中的操作符重载详细解析C++-操作符重载、并实现复数类详解



c+ 重载 运算符 运算符重载 C++

需要 登录 后方可回复, 如果你还没有账号请 注册新账号