友元类和友元函数是C++的一个总要的特性。友元类的所有函数都可以访问原始类的私有成员和保护成员。因此尽管友元被授予从外部访问类的私有部分的权限,但它并不与面向对象的编程思想矛盾,相反它提高了共有接口的灵活性。
友元声明可以位于公有、私有或者保护部分,其所在的位置无关紧要。
友元就行朋友一样可以把隐私部分公开出来,和朋友分享。
#pragma once
#include <string>
#include "ColorPainter.h"
class CarA {
friend class Person;
friend void ColorPainter::setCarColor(CarA* car, std::string color);
public:
CarA();
~CarA();
void setCarName(std::string name) {
_carName = name;
}
std::string getCarName() {
return _carName;
}
void setCarColor(std::string color) {
_carColor = color;
}
std::string getCarColor() {
return _carColor;
}
private:
std::string _owner;//拥有者
std::string _carName;//汽车名称
std::string _carColor;//汽车颜色
};
#include "CarA.h"
CarA::CarA() {
}
CarA::~CarA() {
}
#pragma once
class CarA;
class Person {
public:
Person();
~Person();
void setCar(CarA* car);
private:
CarA* _car = nullptr;
};
#include "Person.h"
#include "CarA.h"
Person::Person() {
}
Person::~Person() {
}
void Person::setCar(CarA* car) {
_car = car;
_car->_owner = "wwww";
}
#pragma once
#include <string>
//汽车喷漆工
class CarA;
class ColorPainter {
public:
ColorPainter();
~ColorPainter();
void setCarColor(CarA* car, std::string color);
};
#include "ColorPainter.h"
#include "CarA.h"
ColorPainter::ColorPainter() {
}
ColorPainter::~ColorPainter() {
}
void ColorPainter::setCarColor(CarA* car,std::string color) {
car->_carColor = color;
}
aaa