一、实验目的
1、掌握成员函数重载运算符。
2、掌握友元函数重载运算符。
3、理解并掌握引用在运算符重载中的作用。
二、实验内容
1、掌握成员函数重载运算符。
2、掌握友元函数重载运算符。
3、理解并掌握引用在运算符重载中的作用。
二、实验内容
1、定义空间中的点类(有x,y,z坐标),并重载其++和—运算符。编写主函数对该类进行应用。
#include<iostream>
using namespace std;
class Point
{
private:
int x,y,z;
public:
Point(int a=0,int b=0,int c=0);
Point operator ++();
Point operator ++(int);
Point operator --();
Point operator --(int);
void print();
};
int main()
{
Point ob1(2,3,4),ob2;
++ob1;
ob1.print();
ob2=ob1++;
ob2.print();
ob1.print();
--ob1;
ob1.print();
ob2=ob1--;
ob2.print();
ob1.print();
return 0;
}
Point::Point(int a, int b,int c)
{
x=a;
y=b;
z=c;
}
void Point::print()
{
cout<<'('<<x<<','<<y<<','<<z<<')'<<endl;
}
Point Point::operator ++()
{
++x;
++y;
++z;
return *this;
}
Point Point::operator ++(int)
{
Point temp=*this;
x++;
y++;
z++;
return temp;
}
Point Point::operator --()
{
--x;
--y;
--z;
return *this;
}
Point Point::operator --(int)
{
Point temp=*this;
x--;
y--;
z--;
return temp;
}
2、定义一个复数类,并通过定义运算符重载实现两个复数可以判别是否相等(==),并给出主函数应用该类。
#include<iostream>
#include<iomanip>
using namespace std;
class com
{
private:
int real,imag;
public:
com(int a,int b);
void operator ==(com b);
};
int main()
{
com ob1(2.2,3.3),ob2(2.2,3.3);
ob1==ob2;
return 0;
}
com::com(int a,int b)
{
real=a;
imag=b;
}
void com::operator ==(com b)
{
if((real==b.real)&&(imag==b.imag))
{
cout<<"两复数相等!!"<<endl;
}
else
{
cout<<"两复数不相等!!"<<endl;
}
}