Is it possible in class C to perform the calculation int a / int b and write the result in a variable of class C int c ?
class A { int a = 5; }; class B { int b = 10; }; class C { friend class A; friend class B; int c; }; Is it possible in class C to perform the calculation int a / int b and write the result in a variable of class C int c ?
class A { int a = 5; }; class B { int b = 10; }; class C { friend class A; friend class B; int c; }; If you are interested in the question of whether a friendly class can use private class names, whose friend it is, then yes — for example:
#include <iostream> using std::cout; class C; // вначале обьявите class A { friend class C; int a; public: A() : a(10) { } // в конструкторе инициализировать, а не так как вы сделали }; class B { friend class C; int b; public: B() : b(5) {} }; class C { int c; // с это не C, поэтому можно public: C() { A t; B k; c = ta/kb;} // нужно создавать обьекты типов int get_res() const { return c; } }; int main() { C g; std::cout << g.get_res(); return 0; } You see, if I say that you are my friend - you are not letting me out of my statement from me to spend the night?
But I sort of should, once stated that you are my friend ...
This is how you have - class C stated that he is a friend of A and B , so he trusts his insides to them :) And they did not express such confidence to him.
Agree, it would be too insecure - so any class, any function could get access to any hidden fields - just announcing your desire ...
In your example, there is no a and there is no b .
In your example, there are only non-static fields of the classes A::a and B::b . Non-static class fields do not exist physically by themselves. Non-static class fields exist only inside objects (instances) of these classes, only together with these objects. Therefore, until you create objects of these classes, there will be no a and b .
If you have an instance of aa class A and an instance of bb class B , then you can easily calculate the value of aa.a / bb.b if you have the appropriate access rights. But as long as you do not have such instances, there is nothing to talk about, for no a and b exist.
In your code, I do not see the slightest hint that class C works with some instances of classes A and B And without instances of any a and b and can not speak.
Source: https://ru.stackoverflow.com/questions/771717/
All Articles