友元(friend)
全局函数/类/成员函数都可以作友元
全局函数作友元 从而访问私有成员
#include <iostream>
#include<string>
using namespace std;
class fz
{
friend void hpy(fz* fz);//将hpy函数设置为fz类的友元
public:
fz()
{
m_kt = "客厅";
m_ws = "卧室";
}
public:
string m_kt;
private:
string m_ws;
};
void hpy(fz *fz)
{
cout << fz->m_kt << endl;
cout << fz->m_ws << endl;//友元函数可以访问类内私有成员
}
int main()
{
fz fz1;
hpy(&fz1);
return 0;
}
类作为友元 访问 其他类内私有成员
#include <iostream>
#include<string>
using namespace std;
class Building
{
friend class goodGay;
public:
string m_kt;
public:
Building();
private:
string m_ws;
};
Building::Building()
{
m_kt = "客厅";
m_ws = "卧室";
}
class goodGay
{
public:
goodGay();
void visit();
Building* bd;
private:
};
void goodGay::visit()
{
cout << bd->m_kt << endl;
cout << bd->m_ws << endl;
}
goodGay::goodGay()
{
bd = new Building;
}
int main()
{
goodGay gg;
gg.visit();
return 0;
}
成员函数作友元
#include <iostream>
#include <string>
using namespace std;
class building
{
//friend class goodGay;
friend void goodGay::visit();
public:
building();
~building();
string m_kt;
private:
string m_ws;
};
building::building()
{
m_kt = "客厅";
m_ws = "卧室";
}
building::~building()
{
}
class goodGay
{
public:
goodGay();
void visit();
void visit2();
building* bd;
~goodGay();
private:
};
goodGay::goodGay()
{
bd = new building;
}
goodGay::~goodGay()
{
}
void goodGay::visit()
{
cout << bd->m_kt << endl;
cout << bd->m_ws << endl;
}
void goodGay::visit2()
{
cout << bd->m_kt << endl;
}
int main()
{
goodGay* g1 = new goodGay;
g1->visit();
g1->visit2();
return 0;
}
加号运算符重载(operator+ )可以发生重载
#include <iostream>
#include <string>
using namespace std;
class person
{
public:
person();
~person();
//person operator+(person &p);
int m_a;
int m_b;
private:
};
person::person()
{
}
person::~person()
{
}
/*person 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;
}
*/
/**/person operator+(person& p1, person& p2)
{
person temp;
temp.m_a = p1.m_a + p2.m_a;
temp.m_b = p1.m_b + p2.m_b;
return temp;
}
void test01()
{
person p1;
p1.m_a = 10;
p1.m_b = 10;
person p2;
p2.m_a = 11;
p2.m_b = 12;
//p3 = p1.operator+(p2);//成员函数本质调法
//p3 = operator+(p1,p2);//全局函数本质调法
person p3 = p1 + p2;
cout << p3.m_a << endl;
cout << p3.m_b << endl;
}
int main()
{
test01();
return 0;
}
|