在C 的程序中使用2类,并最多找到2个数字

Program in c++ to use 2 classes and find maximum of 2 numbers

本文关键字:数字 2个 2类 程序      更新时间:2023-10-16

我想找到2个数字的最大值,但是我需要使用2个类和朋友函数,而不是简单的方法。如何实施它?我正在使用以下代码,但代码不起作用。

#include<iostream>
using namespace std;
class one
{
    int a;
    public:
    friend int cal(one a);
};
class two
{
    int b;
    public:
    friend int cal(one a,two b);
};
 cal(int f,int g)
{
    int ans=(x.a>y.b)?x.a:y.b;
}
int main()
{
    one x;
    two y;
    cal(10,20);
}
#include<iostream>
using namespace std;
class biggest
{
   private:
    int a,b;
    public:
        void input();
            void display();

};
void biggest::input()
{
    cout<<"Enter 2 nos.:";
    cin>>a>>b;
}
void biggest::display()
{
    if(a>b)
    cout<<"Biggest no.:"<<a;
    else
    cout<<"Biggest no.:"<<b;
}
int main()
{
    biggest b;
    b.input();
    b.display();

}

输出

输入2号:133 21

样本输出

最大号:133

通过将函数设置为"朋友",您可以使其访问类的私人成员。例子看起来真的很奇怪,但我想这会做到。这两个课程都使私人会员访问" CAL"功能。

#include<iostream>
using namespace std;
class one;
class two;
class one
{
    int a = 10;
    public:
    friend int cal(one a,two b);
};
class two
{
    int b = 20;
    public:
    friend int cal(one a,two b);
};
int cal(one x,two y)
{
    return (x.a>y.b)?x.a:y.b;
}
int main()
{
    one x;
    two y;
    cout << cal(x,y);
}