C++ friend的使用

友元类和友元函数是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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wb175208

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值