掌握C++运算符重载

1 实验内容及目的

l 实验目的

理解和掌握C++运算符重载。

l 实验内容


实现Circle类,在程序清单给出的Circle类中实现关系运算符(<、<=、==、!=、>、>=),实现按半径对Circle对象排序。

 

2 实验步骤

(1)实现类

l Circle类

 


(2)编写测试程序 

创建若干个Circle对象,运用重载的运算符按半径对其进行排序。

 

3 源代码

头文件:

class Circle {

private:

double radius;

 

public:

Circle();

Circle(double r);

double getRadius();

void setRadius(double r);

double getArea();

 

bool operator <(Circle c);

bool operator <=(Circle c);

bool operator ==(Circle c);

bool operator !=(Circle c);

bool operator >(Circle c);

bool operator >=(Circle c);

};

源文件:

#include <stdio.h>

#include <iostream>

#include <math.h>

#include "Circle.h"

using namespace std;

 

Circle::Circle() {

radius = 0;

}

 

Circle::Circle(double r) {

radius = r;

}

 

double Circle::getRadius() {

return radius;

}

 

void Circle::setRadius(double r) {

radius = r;

}

 

double Circle::getArea() {

return radius * radius * 3.14;

}

 

bool Circle::operator <(Circle c) {

if(this->radius < c.getRadius()) return true;

else return false;

}

 

bool Circle::operator <=(Circle c) {

if(this->radius <= c.getRadius()) return true;

else return false;

}

 

bool Circle::operator ==(Circle c) {

if(this->radius == c.getRadius()) return true;

else return false;

}

 

bool Circle::operator !=(Circle c) {

if(this->radius != c.getRadius()) return true;

else return false;

}

 

bool Circle::operator >(Circle c) {

if(this->radius > c.getRadius()) return true;

else return false;

}

 

bool Circle::operator >=(Circle c) {

if(this->radius >= c.getRadius()) return true;

else return false;

}

测试文件:

#include <stdio.h>

#include <iostream>

#include "Circle.h"

using namespace std;

 

void main() {

int r;

int size = 5;

Circle sourse[5];

Circle buffer[5];

Circle coral;

cout << "Please inputting 5 Circle's radius:" << endl;

for(int i = 1; i <= size; i++) {

cout << "Circle" << i << "'s radius is: ";

cin >> r;

sourse[i-1].setRadius(r);

buffer[i-1].setRadius(r);

}

 

for(int j = 0; j < size - 1; j++) {

int min = j;

for(int k = j + 1; k < size; k++) {

if(buffer[min] > buffer[k]) min = k;

}

coral = buffer[j];

buffer[j] = buffer[min];

buffer[min] = coral;

}

cout << endl;

cout << "The order of Circles' radius is:" << endl;

 

for(int m = 0; m < size; m++) {

for(int n = 1; n <= size; n++) {

if(buffer[m] == sourse[n-1]) break;

}

cout << buffer[m].getRadius();

cout << " (Circle" << n << ")" << endl;

}

 

}

 

4 遇到的问题与分析

1. 刚开始并不知道需要把符号 重载,只是单纯的对圆的对象进行半径比较。

分析:通过看书和上课听老师讲解,正确的对符号进行重载从而,能进行对象的比较。

 

5 实验体会

通过该实验,基本上掌握了运算符的重载方法,但相对于更为全面的重载方法,这只是简单的基础过程。由此需要在日后的学习和实际运用中对相关方面的知识作进一步的探究。

此外,通过此次实验过程,让我感受到程序编码扩展的必然性。只有在符合个人需求的功能定义上,才能够真正地实现所提供的功能的意义。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值