第二篇关于C++类与对象的笔记重点在于友元与运算符重载
1友元
友元是特殊的声明,实现对于某个类的private的访问,关键字是friend。
有趣的是,C++中private私有的类的父子均无权访问,但朋友firend却可以访问。
友元大致分为三类:
1、全局函数友元
2、类友元
3、成员函数友元(注意作用域)
2运算符重载
大抵实现了-、- -、=、==、<<、()六种运算符重载。
注意点:
递减(递增)运算符重载分为前置与后置两种类型
前置:返回自身,实现反复调用(链式)
后置:返回值,无法反复调用
<<运算符重载使用全局函数重载,其余则成员函数与全局函数都可以
()运算符重载又被成为仿函数
=赋值运算符重载仍然需要考虑深浅拷贝问题。
#include<iostream>
#include<string>
using namespace std;
//友元&运算符重载
class Cperson
{
//全局函数作友元
//全局函数visit_diary可以访问Cperson中私有成员diary
friend string visit_diary(Cperson &p);
//类作友元
//CGoodfriend友元可以反问Cperson中私有成员diary
friend class CGoodfriend;
//成员函数作友元
//CGoodfriend中成员函数visit2()可以访问私有成员
//即使上一行代码被注释(CGoodfriend不再是友元),也依旧可以访问
friend void CGoodfriend::visit2();
public:
string m_name;
string m_idnumber;
int m_age;
int *m_height;
Cperson() {};
Cperson(string name,string id,int age,int height)
{
m_name = name;
m_idnumber = id;
m_age = age;
m_height = new int(height);
m_diary = "secret";
}
Cperson(const Cperson &p)
{
this->m_age = p.m_age;
this->m_idnumber = p.m_idnumber;
this->m_name = p.m_name;
this->m_height = new int(*p.m_height);
}
~Cperson()
{
if (m_height != NULL)
{
delete m_height;
m_height = NULL;
}
}
//成员函数 减号运算符重载
Cperson operator-(const Cperson &p)
{
Cperson p3;
p3.m_age = this->m_age - p.m_age;
return p3;
}
//成员函数 前置递减重载
//返回引用 实现反复调用(链式)
Cperson& operator--()
{
--m_age;
return *this;
}
//成员函数 后置递减重载
Cperson operator--(int)//占位参数
{
Cperson temp = *this;
temp.m_age--;
return temp;
}
//成员函数 ==重载
bool operator==(Cperson &p)
{
if (this->m_age == p.m_age&&this->m_name == p.m_name&&this->m_idnumber == p.m_idnumber)return 1;
else return 0;
}
//成员函数 赋值=重载(注意深浅拷贝)
Cperson& operator=(Cperson &p)
{
this->m_age = p.m_age;
this->m_idnumber = p.m_idnumber;
this->m_name = p.m_name;
//深拷贝
if (this->m_height != NULL)
{
delete this->m_height;
m_height = NULL;
}
this->m_height = new int(*p.m_height);
return *this;
}
//仿函数||符号()重载
void operator()()
{
cout << "这是一个人对象" << endl;
}
private:
string m_diary;
};
string visit_diary(Cperson &p)
{
cout << "p的日记为:" << p.m_diary << endl;
return p.m_diary;
}
//全局函数重载<<
//返回引用,实现链式结构
ostream& operator<<(ostream out, Cperson &p)
{
out << "p的信息如下:" << endl << "age:" << p.m_age << endl << "height:" << *p.m_height << endl;
return out;
}
class CGoodfriend
{
public:
CGoodfriend()
{
p = new Cperson();
}
void visit()
{
cout << "p的日记:" << (*p).m_diary << endl;
}
void visit2()
{
cout << "p的日记:" << (*p).m_diary << endl;
}
private:
Cperson *p;
};
2020.5.4