Pergunta

i am new to c++ programming, can we declare some members of class as friend to other class. it means Lets say Class A have three member functions and instead of declaring whole class as friend to other Class B (say) can i declare only one member of class A as friend to Class B, so please help.

Foi útil?

Solução 2

Yes you can declare a single member function as friend of another class.
Online Sample:

#include<iostream>
class Myclass;
class Otherclass
{
    public:
      void doSomething(Myclass &obj);

};
class Myclass
{
    int i;
    friend void Otherclass::doSomething(Myclass &obj);
};
void Otherclass::doSomething(Myclass &obj)
{
    obj.i = 10;
    std::cout<<obj.i;
}


int main()
{
    Myclass obj;
    Otherclass obj2;
    obj2.doSomething(obj);
    return 0;
}

Outras dicas

Yes:

class A
{
    public:
        void func_1();
        void func_2();
        void func_3();
};

class B
{
    friend void A::fund_2();
    void plop(); // only A::func_2() can call this function
};

On declaration of a friend class all member functions of the friend class become friends of the class in which the friend class was declared. source

Not to be harsh on you, but look what I found by simply Googling "c++ friend class functions":

Friend Functions And Classes

...and about 200 more.

yes.

For an example, ask wiki (they know everything):

http://en.wikipedia.org/wiki/Friend_function

Or do a basic search ...

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top