第十一站:运算符重载operate(+-*/)

本文详细介绍了C++中如何使用成员函数和友元函数重载运算符,包括加法、比较、下标和输入输出操作。同时讨论了赋值运算符、bug以及类类型之间的转换,如普通类型转为类类型和类类型转为普通类型。
摘要由CSDN通过智能技术生成

目录

 使用成员函数重载运算符

 使用非成员函数重载运算符

 使用重载函数运算整数

禁区: 

 赋值重载运算符=

bug:

 关系重载运算符><

下标运算符重载

 bug

输入输出运算符重载<<,>>

使用成员函数

使用友元函数 (更方便)

 普通类型==>类类型

 类类型==>普通类型

类类型转换成类类型(拷贝)


operate(+,-,*,/,=,->,<<,>>)支持使用友元函数

(),=,->,[]不支持使用友元函数

局限:C/C++的运算符,支持的数据类型,仅限于基本数据类型

 使用成员函数重载运算符

 //一只牛+一只羊
Pig operator+(const Goat& goat);//一个参数是本类,一个是goat类,返回值是pig类
//一只牛+一只牛
Pig operator+(const Cow& cow);

//相当于将值返回给猪,牛.operate+(羊)
Pig Cow::operator+(const Goat& goat){
    int tmp = this->weight * 2 + goat.getWeight() * 3;
    return Pig(tmp);
}
Pig Cow::operator+(const Cow& cow) {
    int tmp = (this->weight + cow.weight) * 2;
    return Pig(tmp);
}

    cout << "牛牛相加得:";
    Cow h1(100);
    Cow h2(200);
    Pig p1 = h1+h2;

    cout << p1.describe() << endl;

  使用非成员函数重载运算符

 friend Pig operator+(const Cow& cow, const Goat& goat);
friend Pig operator+(const Cow& cow, const Cow& cow1);

Pig operator+(const Cow& cow, const Goat& goat) {
    int tmp = cow.weight * 2 + goat.getWeight()*3;
    return tmp;
}

Pig operator+(const Cow& cow , const Cow& cow1) {
    int tmp = cow.weight * 2 + cow1.weight * 2;
    return tmp;
}

cout << "牛牛相加得:";
Cow h1(100);
Cow h2(200);
Pig p1 = operator+(h1,h2);
cout << p1.describe() << endl;

 使用重载函数运算整数

Pig operator+(int n);//一个参数是本身,一个是整数n,,返回值是pig类

禁区: 

不能对标准运算符进行重载:1+1=2

不能改变原运算符的语法规则,单目运算符不能变为双目运算符

不能改变运算符的优先级

不能创造新的运算符(错:operator**)

(),=,->,[]不支持使用友元函数 

 赋值重载运算符=

.h 

#pragma once
#include <string>
#include <iostream>
using namespace std;
class Boy{
public:
	Boy(const char* name=NULL, int age=0, int salary=0, int darkHorse=0);
	Boy& operator=(const Boy& boy);
	~Boy();

    string decribe();
private:
	char* name;
	int age;
	int salary;
	int darkHorse;
	unsigned int id;
	static int LAST_ID;
};

 .cpp

#include "Boy.h"
#include <string>
#include <sstream>
int Boy::LAST_ID = 0;//编号初始化为0

Boy::Boy(const char* name, int age, int salary, int darkHorse){
	if (!name){
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值