CPP 054 – Friends

Sınıfın dışındaki fonksiyonlar sınıfın içindeki private ve protected alandaki değişkenlere erişemez. Eğer erişmesini istiyorsak friend keyword’ünü kullanıyoruz.

// main.cpp
#include <iostream>
using namespace std;

class XYZ {
	int x,y,z;

	friend void setX(XYZ& xyz, int x);
	friend void setY(XYZ& xyz, int y);
	friend void setZ(XYZ& xyz, int z);

	friend void print(XYZ& xyz) {
		cout << xyz.x << ", " << xyz.y << ", " << xyz.z << endl;
	}
};

int main() {
	XYZ var;
	setX(var, 3);
	setY(var, 4);
	setZ(var, 5);

	print(var); // 3, 4, 5
}

void setX(XYZ& xyz, int x) {
	xyz.x = x;
}
void setY(XYZ& xyz, int y) {
	xyz.y = y;
}
void setZ(XYZ& xyz, int z) {
	xyz.z = z;
}

A friend function is a function that isn’t a member of a class but has access to the class’s private and protected members. Friend functions aren’t considered class members; they’re normal external functions that are given special access privileges. Friends aren’t in the class’s scope, and they aren’t called using the member-selection operators (. and –>) unless they’re members of another class. A friend function is declared by the class that is granting access. The friend declaration can be placed anywhere in the class declaration. It isn’t affected by the access control keywords.

https://learn.microsoft.com/en-us/cpp/cpp/friend-cpp?view=msvc-170


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *