【发布时间】:2021-06-05 07:59:18
【问题描述】:
// 创建名为 Class1 和 Class2 的类,每个类都有一个私有成员。添加成员函数以在每个类上设置一个值(比如 setValue)。再添加一个对两个类都友好的函数 max(),max() 函数应该比较两个类的两个私有成员并显示它们之间的最大值。为每个类创建一个对象并为其设置一个值。显示其中的最大个数
#include <iostream>
using namespace std;
class Class1
{
int a;
public:
int setValue();
friend int max();
};
class Class2
{
int b;
public:
int setValue();
friend int max();
};
int Class1::setValue()
{
cout<<"Enter the first number:";
cin>>a;
}
int Class2::setValue()
{
cout<<"Enter the second number:";
cin>>b;
}
int max()
{
Class1 c1;
Class2 c2;
if(c1.a>c2.b)
{
cout<<"Greater number: "<<c1.a<<endl;
}
else
{
cout<<"Greater number: "<<c2.b<<endl;
}
}
int main()
{
Class1 obj1;
Class2 obj2;
obj1.setValue();
obj2.setValue();
cout<<endl;
max();
return 0;
}
【问题讨论】:
-
max函数创建两个新对象并比较它们。那是你要的吗?也许您想将要比较的对象作为参数传递给函数。
标签: c++