问题及代码:
/*
*Copyright (c) 2015,烟台大学计算机学院
*All rights reserved.
*文件名称:text.cpp
*作者:徐健
*完成日期:2015年5月14日
*版本号:v1.0
*
*问题描述: 通过运行程序理解运算符重载的意义
*输入描述: 无
*程序输出: 运算符重载后的运算结果
*/
#include <iostream>
using namespace std;
class Sample
{
private :
int x;
public :
Sample(){}
Sample (int a){x=a;}
void disp(){cout<<"x="<<x<<endl;}
friend Sample operator+(Sample &s1,Sample &s2);
};
Sample operator +(Sample &s1,Sample &s2)
{
return Sample (s1.x+s2.x);
}
int main()
{
Sample obj1(10);
Sample obj2(20);
Sample obj3;
obj3=obj1+obj2;
obj3.disp();
return 0;
}
运行结果:
知识点总结:
运算符重载使我们可以多样化的对程序进行创造。
学习心得:
此项目主要使用了双目运算符的重载,并且是以非成员函数的方法实现的,要注意当运算符重载时要将其声明为友元函数。