友元--friend
友元可以访问类的私有属性
class Person
{
friend void test();
public:
Person(int n)
{
this->n = n;
}
private:
int n;
};
void test()
{
Person p(20);
cout << p.n << endl;
}
int main()
{
test();
system("pause");
return 0;
}
友元可以是友类、友函数、成员函数
重载运算符--operator
#include <iostream>
using namespace std;
class Person
{
friend void test();
friend Person operator+(Person &p1, Person p2);
public:
Person(){};
Person(int a,int b)
{
m_a = a;
m_b = b;
}
private:
int m_a;
int m_b;
};
Person operator+(Person &p1, Person p2)
{
Person tmp ;
tmp.m_a = p1.m_a + p2.m_a;
tmp.m_b = p1.m_b+ p2.m_b;
return tmp;
}
void test()
{
Person p1(10, 10);
Person p2(20, 20);
Person p3 = p1 + p2;
cout << "p3.m_a= " << p3.m_a << "p3.m_b= " << p3.m_b << endl;
}
int main()
{
test();
system("pause");
return 0;
}