4.4 友元
一种权限控制的方法,让类外的一些函数或类能访问类的私有属性。
关键字为friend
友元的三种形式:
全局函数friend void goodGay(Building &building);
类friend class GoodGay
成员函数friend void GoodGay::visit();
4.4.1 全局函数 友元
class Building{
//友元声明
friend void goodGay(Building &building);
public:
Building(){
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
public:
string m_SittingRoom;
private:
string m_BedRoom;
};
//全局函数
void goodGay(Building &building){
cout<< building.m_SittingRoom<<endl;
cout<< building.m_BedRoom<<endl;//友元函数可以访问私有属性
}
4.4.2 类做友元
class Building;
class GoodGay{
public:
GoodGay();
void visit();
Building * building;
};
class Building{
//声明GoodGay类是 本类的友元
friend class GoodGay;
public:
Building();
public:
string m_SittingRoom;
private:
string m_BedRoom;
};
//类外实现:
Building::Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
GoodGay::GoodGay()
{
building = new Building;
}
void GoodGay::visit()
{
cout<<building->m_SittingRoom;
cout<<building->m_BedRoom;
}
4.4.3 成员函数做友元
只让某个类的某个成员函数 可以访问自己的私有属性。 在类中声明该类的该函数为友元: 例如,让GoodGay的visit()可以访问Building的私有属性:
class Building
{
friend void GoodGay::visit();
public:
...
private:
...
};
4.5 运算符重载
对已有的运算符重新定义,赋予其另一种功能以适应不同的数据类型。
4.5.1 加号运算符重载
operator+
通过成员函数重载
Person operator+(Person &p){
Persom temp;
temp.A = this->A + p.A;
temp.B = this->B + p.B;
return temp;
}
通过全局函数重载
Person operator+(Person &p1, Person &p2){
Persom temp;
temp.A = p1.A + p2.A;
temp.B = p1.B + p2.B;
return temp;
}
然后可以使用:
Person p3 = p1 + p2 ; //调用重载的operator+
4.5.2 <<左移运算符重载
输出对象。 通过全局函数重载:
ostream & operator<<(ostream& out, Person &p) {
out<<p.A<<" "<<p.B;
}
又因为我们一般将属性设置为私有,所以为了让这个全局函数能访问私有属性,还要将它设置为友元。
4.5.3 递增运算符重载
MyInteger& operator++()
后++,用int做占位参数,区分前++和后++。MyInteger operator++(int)
MyInteger operator++(int){
MyInteger temp = *this;
n_Num ++;
return temp;
}
将++改为--就是自减运算符。
4.5.4 赋值运算符重载
Person& operator=(Person &p)
解决浅拷贝问题。自己在赋值运算符中使用深拷贝(申请内存)
4.5.5 关系运算符重载
bool operator==(Person &p)
bool operator!=(Person &p)
4.5.6 函数调用运算符重载
括号重载operator()
也称仿函数。
写法灵活。
class MyPrint{
public:
//重载()
void operator()(string test){
cout << test << endl;
}
};
...
MyPrint mprint;
mprint("hello"); //使用类似函数调用,因此称为仿函数