4.4 友元
4.4.1 全局函数做友元
友元的目的就是为了让一个类或者一个函数访问另一个类中的私有成员。 全局函数做友元就是让全局函数访问类中的私有成员。
class Building
{
friend void goodGuy(Building *building);
public:
Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
public:
string m_SittingRoom;
private:
string m_BedRoom;
};
void goodGuy(Building *building)
{
cout << "全局函数:" << building->m_SittingRoom << endl;
cout << "全局函数:" << building->m_BedRoom << endl;
}
void test01()
{
Building building;
goodGuy(&building);
}
4.4.2 类做友元
类做友元,目的就是让一个类可以访问另一个类的私有成员。
class Building;
class GoodGuy{
public:
GoodGuy();
void visit();
Building *building;
};
class Building{
friend class GoodGuy;
public:
Building();
public:
string m_SittingRoom;
private:
string m_BedRoom;
};
Building::Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
GoodGuy::GoodGuy() {
building = new Building;
}
void GoodGuy::visit() {
cout << "GoodGuy is called. ->" << building->m_SittingRoom << endl;
cout << "GoodGuy is called. ->" << building->m_BedRoom << endl;
}
void test01()
{
GoodGuy gg;
gg.visit();
}
4.4.3 成员函数做友元
GoodGuy里面的成员函数做友元。
class Building;
class GoodGuy{
public:
GoodGuy();
void visit();
void visit02();
private:
Building *building;
};
class Building{
friend void GoodGuy::visit();
public:
Building();
public:
string m_SittingRoom;
private:
string m_BedRoom;
};
GoodGuy::GoodGuy() {
building = new Building;
}
Building::Building() {
this->m_SittingRoom = "keting";
this->m_BedRoom = "woshi";
}
void GoodGuy::visit()
{
cout << building->m_SittingRoom << endl;
cout << building->m_BedRoom << endl;
}
void GoodGuy::visit02()
{
cout << building->m_SittingRoom << endl;
}
void test()
{
GoodGuy gg;
gg.visit();
gg.visit02();
}
4.5 运算符重载
重载的运算符是带有特殊名称的函数,函数名是由关键字 operator 和其后要重载的运算符符号构成的。可以对类对象进行自定义操作。 但是也要注意:内置数据类型是不能重载的; 也不能滥用。
4.5.1 加法运算符重载
class person{
public:
person operator+(person &p)
{
person temp;
temp.m_A = this->m_A + p.m_A;
temp.m_B = this->m_B + p.m_B;
return temp;
}
int m_A;
int m_B;
};
person operator+(person &p1, int num)
{
person temp;
temp.m_A = p1.m_A + num;
temp.m_B = p1.m_B + num;
return temp;
}
void test01()
{
person p1;
p1.m_A = 10;
p1.m_B = 10;
person p2;
p2.m_A = 10;
p2.m_B = 10;
person p3 = p1.operator+(p2);
person p4 = p1 + 100;
cout << "p3.m_A = " << p3.m_A << endl;
cout << "p3.m_B = " << p3.m_B << endl;
cout << "p4=" << p4.m_A << " " << p4.m_B << endl;
}
|