#include<iostream>
#include<string>
using namespace std;
class book
{
public:
book(){}
book(string name,int num):name(name),num(num){}
void print()
{
cout << this->name << ":" << this->num << endl;
}
//重载函数
friend book operator+(book object1, book object2);
//类的成员函数的方式重载
//减法
book operator-(book object)//this:BOOK object:BO
{
return book(this->name, this->num - object.num);
}
string& get_name()
{
return name;
}
int& get_num()
{
return num;
}
protected:
string name;
int num;
};
//友元重载
book operator+(book object1, book object2)
{
return book(object1.name+ object2.name, object1.num+ object2.num);
}
int main()
{
book BO("三国", 201);
book BOOK("水浒传", 202);
//重载函数隐式调用
book object = BO + BOOK; //所有重载实质都是函数调用
//重载函数的显式调用
//operator+解析为函数名
book novel = operator+(BO, BOOK);//需要两个参数是因为是在类外
book BOO = BOOK - BO;
BOO.print();
object.print();//this代表object
novel.print();//this代表novel
book BOOK1 = BO.operator-(BOOK);
BOOK1.print();
return 0;
}
特殊运算符
#include<iostream>
#include<string>
using namespace std;
class Num
{
public:
Num(){}
Num(int iNum=0):iNum(iNum){}
Num operator++(int) //后置的++或者--需要加一个无效参数,eg:int
{
return Num(this->iNum++);
}
Num operator++() //前置的++
{
return Num(++this->iNum);
}
void print()
{
cout << iNum << endl;
}
int& get_num()
{
return iNum;
}
protected:
int iNum;
};
int main()
{
Num a(1);
Num b = a++;//a.operator++()
b.print();//1
a.print();//2
Num d = ++a;//3
a.print();//3
d.print();//3
return 0;
}
operator隐式转换
#include<iostream>
using namespace std;
class book
{
public:
book(string name=" ",int num=0):name(name),num(num){}
void print()
{
cout << name << "\t" << num << endl;
}
//operator 要转的类型() { return 返回相应类型的数据;};
operator int()
{
return this->num;
}
protected:
string name;
int num;
};
int main()
{
book object("三国",201);
object.print();
//赋值操作的隐式转换
int sum = object;
cout << sum << endl;
return 0;
}