【问题标题】:Program in c++ to use 2 classes and find maximum of 2 numbers用 C++ 编程以使用 2 个类并找到最多 2 个数字
【发布时间】:2017-09-08 07:19:05
【问题描述】:

我想找到最多 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);
}

【问题讨论】:

  • 另外,如果我在课程结束后创建课程的对象,它会起作用吗?
  • 听起来有点矫枉过正,但这可能是你的家庭作业的措辞方式。您确定要比较两个不同的类吗?或者这个作业的意思是:用一个类来存储数字,用一个类找到两个这样的数字中的最大值?
  • @CompuChip 是的,作业说要使用 2 个类和朋友功能。但我想不出一个合适的方法。

标签: c++ class friend-function


【解决方案1】:
#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

【讨论】:

    【解决方案2】:

    通过将函数设置为“朋友”,您可以授予它访问类的私有成员的权限。示例看起来真的很奇怪,但我想这会做到。这里的两个类都允许私有成员访问“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);
    }
    

    【讨论】:

    • 请注意,友元函数不需要公开可见性即可访问,但添加一些构造函数会使此代码更通用。
    • @Bob__ 我没有公开朋友功能是出于特定原因,只是因为那里正在进行其他声明。
    猜你喜欢
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 2014-06-09
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多