简体   繁体   English

如何使用 class 的成员 function 作为另一个 ZA2F2ED4F8EBC2CBB4C21A29 的朋友 function

[英]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?) 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.是朋友成员function的正确声明。

The problem is that the class B has no member function max.问题是 class B 没有成员 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.看来您需要的是继承 class B 中的 class A 并将成员 function 最大声明为虚拟 ZC1C425268E6798。

Let's take it practically.让我们实际操作一下。 You have a class A and B class.你有一个 class A 和 B class。 A's max is a friend of B. That's ok. A 的最大值是 B 的朋友。没关系。 You did it right.你做对了。 But this doesn't mean you have A's methods.但这并不意味着你有 A 的方法。 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.同样,您可以使用 A 的最大值(仅使用它)但不能说您是所有者。

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;
 }`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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