简体   繁体   中英

How to use a member function of a class as friend function of another class?

I defined a function which returns the maximum number out of the two integers(belonging to class A).How do I make it work for another class B?(as a friend function of it?)

class A
{ 
    int a;
    int b;
    public:
    void setvalue(){
        a=10;
        b=20;
    }
    int max(){
        if(a>b){
            return a;
        }
        else{
            return b;
        }
    }
};

class B
{

    int c;
    int d;
    public:
    void setvalue(){
        c=10;
        d=20;
    }
    friend int A::max();
};

int main() 
{

    A x;
    x.setvalue();
    cout<<"max is"<<x.max();
    B y;
    y.setvalue();
    cout<<"max is"<<y.max();
    return 0;
}
prog.cpp:38:20: error: 'class B' has no member named 'max'
    cout<<"max is"<<y.max();`

This

friend int A::max();

is a correct declaration of a friend member function.

The problem is that the class B has no member function max. So this expression

y.max()

issues an error.

It seems what you need is to inherit the class A in the class B and declare the member function max as a virtual function.

Let's take it practically. You have a class A and B class. A's max is a friend of B. That's ok. You did it right. But this doesn't mean you have A's methods. In real-life analogy. If you are friend with someone. This doesn't mean you can claim his property. Indeed you can ask your friend to lend you some money, but you can't claim that the property is yours. In same way, you can use A's max(only use it) but can't say that you are owner.

class A
{
public:
int max(int x,int y)
{
            if(x>y)
                        return a;
            return b;
}
class B : public A//this is important
{
            int c ;
}
int main()
 { 
            B y; 
            cout<<"max is"<<y.max(2,3);
             return 0;
 }`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM