// 友元函数
如果一个函数 func(), 它是类A 的友元函数,该函数可以通过A的对象使用A 的所有成员(包括私有成员)
// 定义方式:// 1、在类中写出函数声明
// 2、在函数声明前加一个关键字 friend
// 特点:
// 1、友元函数不是类的内部函数,是一个外部函数,所以没有this 指针
// 2、友元函数的声明不受访问控制符影响,可以放到类的任意位置
// 3、友元函数破坏了类的封装性,轻易不要使用
class Student
{
friend void showS(Student &s);
public:
Student(int id, char *name)
{
this->id = id;
this->name = name;
}
void show(Address &add);
void printS()
{
printf ("id = %d, name = %s\n", id, name);
}
private:
int id;
char *name;
};
// 友元类:如果一个类A 是 类B 的友元类,则类A中所有函数都是类B 的友元函数
class Address
{
friend class Student;
public:
Address(char *s, char *c, char *q, char *cun)
{
shen = s;
city = c;
qu =q;
this->cun = cun;
}
private:
char *shen;
char *city;
char *qu;
char *cun;
};
void Student::show(Address &add)
{
printf ("id = %d, name = %s\n", id, name);
printf ("%s省%s市%s区%s镇\n", add.shen, add.city, add.qu, add.cun);
}
int main()
{
Student s1(1, "小明");
Address add("A","B", "C", "D");
// showS(s1);
s1.show(add);
return 0;
}
运算符重载
#include <iostream>
using namespace std;
// 1 + 2i
class Complex
{
friend Complex add(Complex &c1, Complex &c2);
friend Complex operator+(Complex &c1, Complex &c2);
friend Complex operator+(Complex &c1, int num);
public:
Complex(int a = 0, int b = 0)
{
this->a = a;
this->b = b;
}
void show()
{
printf ("%d + %di\n", a, b);
}
Complex add( Complex &c) // Complex add(Complex*const this, Complex &c)
{
Complex tmp(a+c.a, b+c.b);
return tmp;
}
Complex operator-( Complex &c) // Complex operator-(Complex*const this, Complex &c)
{
Complex tmp(a-c.a, b-c.b);
return tmp;
}
private:
int a; // 实部
int b; // 虚部
};
Complex add(Complex &c1, Complex &c2)
{
Complex tmp(c1.a+c2.a, c1.b+c2.b);
return tmp;
}
// 1、写出函数函数名:operator + 要重载的运算符 operator*、operator-
// 2、根据操作写出函数的形参:operator+(Complex &c1, Complex &c2)
// 3、根据需要写出返回值类型:Complex operator+(Complex &c1, Complex &c2)
// 4、实现功能
Complex operator+(Complex &c1, Complex &c2) // Complex operator+(Complex * const pc, Complex &c2)
{
Complex tmp(c1.a+c2.a, c1.b+c2.b);
return tmp;
}
Complex operator+(Complex &c1, int num)
{
Complex tmp(c1.a+num, c1.b);
return tmp;
}
// 运算符重载,同一种运算,全局方式和内部方式只能存在一种
int main()
{
Complex c1(1,2), c2(3,4),c3;
c3 = c1.add(c2); // add(&c1, c2) ====> c1 + c2
c3 = c2.add(c1); // add(&c2, c1) ====> c2 + c1
// c3 = c1 + c2; // operator+(c1, c2); operator+(&c1, c2);
c3 = c1 - c2; // c1.operator-(c2) ====> operator-(&c1, c2)
c3.show();
c3 = c2 - c1; // c2.operator-(c1) ====> operator-(&c2, c1)
c3.show();
return 0;
}
// 使用全局函数重载运算符
int main1()
{
Complex c1(1,2), c2(3,4),c3;
// 编译器知道如何运算?
// 自定义类型 编译器不知道运算规则,所以不允许直接进行运算
// c3 = add(c1, c2);
// c3 = operator+(c1, c2);
// 1、编译器发现 c1 和 c2 是自定义类型
// 2、它们要进行 + 运算
// 3、调用函数执行相应的功能: operator+(c1, c2)
// 4、如果存在 operator+(c1, c2)则执行成功,如果不存在,则报错
c3 = c1 + c2;
c3.show();
// operator+(c1, 10)
c3 = c1 + 10;
c3.show();
return 0;
}