栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++练习 day6

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++练习 day6

重载时钟

//MyTime.h
#pragma once
#ifndef MYTIME_H_
#define MYTIME_H_
class CMytime {
private:
	int m_hours;
	int m_minutes;
public:
	//CMytime();
	CMytime(int h = 0, int m = 0);//声明构造函数的时候指定默认参数,在定义函数的时候可以不指定默认参数
	void AddH(int h);
	void AddM(int m);
	void reset(int h = 0, int m = 0);
	CMytime operator+(const CMytime &t)const;
	CMytime operator-(const CMytime &t)const;
	CMytime operator*(double  n) const;
	friend CMytime operator*(double m, const CMytime &t) { return t * m; };//为了保证adjusted = 1.5*total
	void show()const;
	~CMytime();

};

#endif

 

//Mytime.cpp
#include
#include "MyTime.h"
using namespace std;



//CMytime::CMytime()
//{
//	m_hours = 0;
//	m_minutes = 0;
//}
CMytime::CMytime(int h, int m )
{
	m_hours = h;
	m_minutes = m;
}
CMytime::~CMytime()
{

}
void CMytime::AddH(int h)
{
	m_hours += h;
}
void CMytime::AddM(int m)
{
	m_minutes += m;
}
void CMytime::reset(int h, int m)
{
	m_hours = h;
	m_minutes = m;
}
CMytime CMytime::operator+(const CMytime &t)const
{
	CMytime sum;
	sum.m_minutes = t.m_minutes + m_minutes;
	sum.m_hours = t.m_hours + m_hours + sum.m_minutes / 60;
	sum.m_minutes = sum.m_minutes%60;
	return sum;
}
CMytime CMytime::operator-(const CMytime &t)const
{
	CMytime diff;
	int top1 = t.m_minutes + 60 * t.m_hours;
	int top2 = m_minutes + 60 * m_hours;
	diff.m_hours = (top2 - top1) / 60;
	diff.m_minutes = (top2 - top1) % 60;
	return diff;
}
CMytime CMytime::operator*(double n)const {
	CMytime result;
	long totalMinutes = m_hours * 60 * n + m_minutes * n;
	result.m_hours = totalMinutes / 60;
	result.m_minutes = totalMinutes % 60;
	return result;
}
void CMytime::show()const
{
	cout << m_hours << "  " << m_minutes;
}
//main
#include
using namespace std;
#include "MyTime.h"
int main(int argc, char* argv[])
{

	CMytime weeding(4, 35);
	CMytime waxing(2, 47);
	CMytime total;
	CMytime diff;
	CMytime adjusted;


	cout << "weeding Time = ";
	weeding.show();
	cout << endl;


	cout << "waxing Time = ";
	waxing.show();
	cout << endl;


	cout << "total work Time = ";   //(1)
	total = weeding + waxing;
	total.show();
	cout << endl;


	diff = weeding - waxing;
	cout << "weeding Time - waxing Time = "; //(2)
	diff.show();
	cout << endl;


	adjusted = total * 1.5;                     //(3)
	cout << "adjusted work Time = ";
	adjusted.show();
	cout << endl;


	return 0;


}

C++运算符重载详解_lishuzhai的专栏-CSDN博客_c++运算符重载为什么要对运算符进行重载:C++预定义中的运算符的操作对象只局限于基本的内置数据类型,但是对于我们自定义的类型(类)是没有办法操作的。但是大多时候我们需要对我们定义的类型进行类似的运算,这个时候就需要我们对这么运算符进行重新定义,赋予其新的功能,以满足自身的需求。C++运算符重载的实质:运算符重载的实质就是函数重载或函数多态。运算符重载是一种形式的C++多态。目的在于让人能够用同名的函https://blog.csdn.net/lishuzhai/article/details/50781753?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522163478120916780269817852%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=163478120916780269817852&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-3-50781753.pc_search_result_cache&utm_term=c%2B%2B%E7%AD%89%E5%8F%B7%E8%BF%90%E7%AE%97%E7%AC%A6%E9%87%8D%E8%BD%BD&spm=1018.2226.3001.4187有复数类Complex,利用运算符重载实现复数的加、减、乘、除等复数运算

//有复数类Complex,利用运算符重载实现复数的加、减、乘、除等复数运算。
#include
using namespace std;
class complex {
private:
	double r, i;
public:
	complex(double R = 0, double I = 0) :r(R), i(I) {};
	complex operator +(complex b);
	complex operator -(complex b);
	complex operator *(complex b);
	complex operator/(complex b);
	void display();
};

complex complex::operator +(complex b) {
	return complex(r + b.r, i + b.i);
}
complex complex:: operator -(complex b)
{
	return complex(r - b.r, i - b.i);
}
//求复数相乘的算法
complex complex::operator *(complex b)
{
	complex t;
	t.r = r*b.r-i*b.i;
	t.i = r * b.i + i * b.r;
	return t;
}
//求复数相除的算法
complex complex::operator /(complex b) {
	complex t;
	double x;
	x = 1 / (b.r*b.r + b.i*b.i);
	t.r = x * (r*b.r + i * b.i);
	t.i = x * (i*b.r - r * b.i);
	return t;
}
void complex::display(){
	cout << r;
	if (i > 0)cout << "+";
	if (i != 0)cout << i << "i" << endl;
}

int main(void) {
	complex c1(1, 2), c2(3, 4), c3, c4, c5, c6;
	complex a, b(2, 3);
	a = b + 2;       			//正确
	// a=2+b;       			//错误   
	a.display();
	c3 = c1 + c2;
	c4 = c1 - c2;
	c5 = c1 * c2;
	c6 = c1 / c2;
	c1.display();
	c2.display();
	c3.display();
	c4.display();
	c5.display();
	c6.display();
	system("pause");
	return 0;
}



//解决前面的2+b问题。
#include


class Complex{
    private:
        double r,i;
    public:
        Complex(double R=0,double I=0):r(R),i(I){};
        friend Complex operator+(Complex a, Complex b);
        friend Complex operator-(Complex a, Complex b);
        friend Complex operator*(Complex a, Complex b);
        friend Complex operator/(Complex a, Complex b);

        friend Complex operator+(Complex a,double b){
            return Complex(a.r+b,a.i);
        }
        friend Complex operator+(double a,Complex b){
            return Complex(a+b.r,b.i);
        }
        
        void display();
};

Complex operator+(Complex a, Complex b){
    return Complex(a.r+b.r,a.i+b.i); 
}
Complex operator-(Complex a, Complex b){
    return Complex(a.r-b.r,a.i-b.i);
}
Complex operator*(Complex a, Complex b){
    Complex t;
    t.r = a.r*b.r-a.i*b.i;
    t.i = a.r*b.i+a.i*b.r;
}
Complex operator/(Complex a, Complex b){
    Complex t;
    double x;
    x = 1/(b.r*b.r+b.i*b.i);
    t.r = x*(a.r*b.r+a.i*b.i);
    t.i = x*(a.i*b.r-a.r*b.i);
    return t;
}

void Complex::display(){
    std::cout<0)
        std::cout<<"+";
    if(i!=0)
        std::cout< 
//设计一个时间类Time,它能够完成秒钟的自增运算。
//设计一个时间类Time,它能够完成秒钟的自增运算。
#include
using namespace std;

class time {
private:
	int hour, minute, second;
public:
	time(int h, int m, int s);
	time operator++();
	//友元重载需要参数
	friend time operator--(time &t);
	void display();
};
time::time(int h, int m, int s)
{
	hour = h;
	minute = m;
	second = s;
	if (hour >= 24)hour = 0;
	if (minute >= 60)minute = 0;
	if (second >= 60)second = 0;
}
time time::operator++()
{
	++second;
	if (second >= 60)
	{
		second = 0;
		++minute;
		if (minute >= 60)
		{
			minute = 0;
			++hour;
			if(hour>=24)
			{
				hour = 0;
			}
		}
	}
	return *this;
}
time operator--(time &t) {
	--t.second;
	if (t.second >= 60) {
		t.second = 0;
		++t.minute;
		if (t.minute >= 60) {
			t.minute = 0;
			++t.hour;
			if (t.hour >= 24)
				t.hour = 0;
		}
	}
	return t;
}
void time::display() {
	cout << hour << ":" << minute << ":" << second << endl;
}
int main(int argc, char const *argv[])
{
	time t1(23, 59, 59);
	t1.display();
	++t1; //隐式调用
	t1.display();
	t1.operator++(); //显式调用
	t1.display();
	time t2(24, 60, 60);
	t2.display();
	++t2;
	t2.display();
	--t2;
	t2.display();
	system("pause");
	return 0;
}

 

//设计一个计数器counter,用类成员重载自增运算符实现计数器的自增,用友元重载实现计数器的自减。
#include
using namespace std;
class Counter {
private:
	int n;
public:
	Counter(int i = 0) :n(i) {};
	Counter operator++();
	Counter operator++(int);
	friend Counter operator--(Counter &c);
	friend Counter operator--(Counter &c, int);
	void display();
};
Counter Counter::operator++() {
	++n;
	return *this;
}
Counter Counter::operator++(int) {//前向自增
	n++;
	return *this;
}
Counter operator--(Counter &c) {
	--c.n;
	return c;
}
Counter operator--(Counter &c, int) {
	c.n--;
	return c;
}
void Counter::display() {
	cout << "counter number=" << n << endl;
}
int main(int argc, char const *argv[])
{
	Counter a;
	++a;
	a.display();
	a++;
	a.display();
	--a;
	a.display();
	a--;
	a.display();
	system("pause");
	return 0;
}

三、重载赋值运算符=

1、赋值运算符“=”的重载特殊性

赋值运算进行时将调用此运算符

只能用成员函数重载

如果需要而没有定义时,编译器自动生成,该版本进行bit-by-bit拷贝

参考:一文说尽C++赋值运算符重载函数(operator=) - 同勉共进 - 博客园

#include
using namespace std;
class X {

		
public:
X &operator=(const X&x)//②加上const,对于const的和非const的实参,函数就能接受;如果不加,就只能接受非const的实参。

	{
		cout << "a:";
		return *this;
	}
};
int main()
{
	X obj1, obj2, obj3;
	obj1 = obj2;          //调用重载“=”
	obj1.operator= (obj2); //调用重载“=”
	obj1 = obj2 = obj3;    //调用重载“=”
	system("pause");
}

 

四、重载赋值运算符[]

1、[ ]是一个二元运算符,其重载形式如下:

class X{
……
		X& operator[](int n);
};

2、重载[]需要注意的问题

  • []是一个二元运算符,其第1个参数是通过对象的this指针传递的,第2个参数代表数组的下标
  • 由于[]既可以出现在赋值符“=”的左边,也可以出现在赋值符“=”的右边,所以重载运算符[]时常返回引用。
  • []只能被重载为类的非静态成员函数,不能被重载为友元和普通函数。
#include
#include
using namespace std;
struct Person {
	double salary;
	char *name;
};
class salaryManager {
	Person *employ;//存放职工信息的数据
	int max;
	int n;
public:
	salaryManager(int Max = 0)
	{
		max = Max;
		n = 0;
		employ = new Person[Max];
	}
	double &operator[](const char *Name) {//这里需要加const,因为输入的是常量
		Person *p;
		for (p = employ; p < employ + n; p++)
		{
			//如果存在的处理
			if (strcmp(p->name, Name) == 0)return p->salary;//strcmp(str1,str2),若str1=str2,则返回零;若str1str2,则返回正数
			p = employ + n++;
			p->name = new char[strlen(Name) + 1];
			strcpy(p->name, Name);
			p->salary = 0;
			return p->salary;
		}
	}
	void display() {
		for (int i = 0; i < n; i++)
		{
			cout << employ[i].name << " " << employ[i].salary << endl;//加[i].之后指针了?
		}
	}
};
int main() {
	salaryManager s(3);
	s["张三"] = 2188.88;
	s["里斯"] = 1230.07;
	s["王无"] = 3200.97;
	cout << "张三t" << s["张三"] << endl;          cout << "里斯t" << s["里斯"] << endl;
	cout << "王无t" << s["王无"] << endl;

	cout << "-------下为display的输出--------nn";
	s.display();
	system("pause");
}

综合练习

#include
#include
using namespace std;
class String {
private:
	int length;//字符长度
	char *sPtr;//存放字符串的指针
	void setString(const char*s2);
	friend ostream &operator<<(ostream &os, String &s)
	{
		return os << s.sPtr;

	}
	friend istream &operator>>(istream &is, String &s)
	{
		return is >> s.sPtr;
	}
public:
	String(const char  * = "");//有些只能在类定义里,比如=、[]、->、()。
	const String &operator=(const String &R)
	{
		length = R.length;
		strcpy(R.sPtr, sPtr);
		return *this;
	}
	const String &operator+=(const String &R);
	bool operator==(const String &R);
	bool operator!=(const String &R);
	bool operator!();//判断字符串是否为空
	bool operator<(const String &R)const;
	bool operator>(const String &R);
	bool operator>=(const String &R);          //字符串的大于等于比较
	char &operator[](int);                     //字符串的下标运算
	~String() {};
};
const String &String::operator+=(const String &R)
{
	char* temp = sPtr;
	length += R.length;
	sPtr = new char[length + 1];
	strcpy(sPtr, temp);
	strcpy(sPtr, R.sPtr);
	return *this;
}
String:: String(const char* str)
{
	sPtr = new char[strlen(str) + 1];
	strcpy(sPtr, str);
	length = strlen(str);
}
bool String::operator==(const String &R){return strcmp(sPtr, R.sPtr) == 0;}
bool String::operator!=(const String &R) { return !(*this == R); }
bool String::operator!() { return length == 0; }
bool String::operator<(const String &R)const { return strcmp(sPtr, R.sPtr) < 0; }
bool String::operator > (const String &R) { return R < *this; }//<在上面已经被重载了
bool String::operator>=(const String &R) { return !(*this  s1结果是 " << (s2 > s1 ? "true" : "false")
		<< "ns2 <  s1结果是 " << (s2 < s1 ? "true" : "false")
		<< "ns2 >= s1结果是 " << (s2 >= s1 ? "true" : "false");
	cout << "nn测试s3是否为空: ";
	if (!s3)
	{
		cout << "s3是空串" << endl; //L3
		cout << "把s1赋给s3的结果是:";
		s3 = s1;
		cout << "s3=" << s3 << "n"; //L5
	}
	cout << "s1 += s2 的结果是:s1="; //L6
	s1 += s2;
	cout << s1; //L7

	cout << "ns1 +=  to you 的结果是:"; //L8
	s1 += " to you";
	cout << "s1 = " << s1 << endl; //L9
	s1[0] = 'H';
	s1[6] = 'N';
	s1[10] = 'Y';
	cout << "s1 = " << s1 << "n"; //L10
	system("pause");
	return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/347526.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号