簡體   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?)

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();`

這個

friend int A::max();

是朋友成員function的正確聲明。

問題是 class B 沒有成員 function max。 所以這個表達式

y.max()

發出錯誤。

看來您需要的是繼承 class B 中的 class A 並將成員 function 最大聲明為虛擬 ZC1C425268E6798。

讓我們實際操作一下。 你有一個 class A 和 B class。 A 的最大值是 B 的朋友。沒關系。 你做對了。 但這並不意味着你有 A 的方法。 在現實生活中類比。 如果你和某人是朋友。 這並不意味着您可以索取他的財產。 事實上,您可以要求您的朋友借給您一些錢,但您不能聲稱該財產是您的。 同樣,您可以使用 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