#include2.左移运算符 重载左移运算符结合友元可以实现自定义输出#include using namespace std; class Person { public: //构造函数 Person(); //析构函数 ~Person(); //error C2673: “operator +”: 全局函数没有“this”指针 //重载加法运算符1 //Person operator+(const Person &p) //{ // Person temp; // temp .m_A = this->m_A + p.m_A; // return temp; //} public: int m_A; }; Person::Person() { m_A = 10; } Person::~Person() { cout<<" ~Person() 析构函数 "< Person temp; temp .m_A = p1.m_A + p2.m_A; return temp; } void fun() { Person p1; Person p2; //Person p3 = p1.operator+(p2);//第一种显式调用方式 Person p4 = p2 + p2;//第一种隐式调用方式 cout<<"p1 m_A : "< //特别注意这种调用方式,类和调用都写在main函数外面,main内部只写一些简单的 fun(); return 0; }
#include3.递增运算符 后置递增运算符先调用当前值,之后对当前值进行递增运算 前置递增运算符先进行递增运算,然后返回的是递增之后的值#include using namespace std; class Person { //友元函数 friend ostream & operator<<(ostream &cout, Person &p); public: //构造函数 Person(); //析构函数 ~Person(); private: int m_A; }; Person::Person() { m_A = 10; } Person::~Person() { cout<<" ~Person() 析构函数 "< cout< Person p1; cout< //特别注意这种调用方式,类和调用都写在main函数外面,main内部只写一些简单的 fun(); return 0; }
#include#include using namespace std; class Int { //友元 friend ostream& operator<<(ostream &cout, Int &p); public: Int();//构造函数 ~Int();//析构函数 //前置++ 返回引用 Int& operator++() { m_Int ++; return *this; } //后置++ 返回值 Int operator++(int) { Int temp = *this; temp.m_Int ++; return temp; } private: int m_Int; }; Int::Int() { m_Int = 0;//初始化 } Int::~Int() { cout<<"析构函数"< cout< Int p; cout<<++p< Int p; cout< //特别注意这种调用方式,类和调用都写在main函数外面,main内部只写一些简单的 fun1(); cout<<"-----------------------------------"<



