目录
类类型转换成类类型(拷贝)
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){