定义猫和老鼠:Cat与Mouse两个类,二者都有weight属性,定义二者的一个友元函数totalweight(),计算二者的重量和。
样例:">裁判测试程序样例:
#include <iostream>
using namespace std;
/* 请在这里填写答案 */
int main()
{
int w1,w2;
cin>>w1>>w2;
Cat tom(w1);
Mouse jerry(w2);
cout<<totalWeight(tom,jerry)<<endl;
}
输入样例:
100 200
输出样例:
300
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
题本身没啥难度,就是要注意一下这道题的大小写,如果友元函数定义和声明不一致,它会提示你,私有成员无法访问,我就是弄错了一个大小写,害的我摸不着头脑
#include<bits/stdc++.h>
using namespace std;
class Mouse; //这里先声明Mouse类,因为Cat类里面友元函数要使用
class Cat
{
private:
int w1;
public:
Cat(int w1)
{
this->w1=w1;
}
friend int totalWeight(Cat C,Mouse M);
};
class Mouse
{
private:
int w2;
public:
Mouse(int w2)
{
this->w2=w2;
}
friend int totalWeight(Cat C,Mouse M); //友元函数的作用就是在类外面,但是可以访问类的私有成员
};
int totalWeight(Cat C,Mouse M)
{
return C.w1+M.w2; //这里是直接调用Cat类和Mouse类的私有成员w1,w2
} //当然你也可以单独写一种返回w1,w2的值得函数
//然后返回这个函数
//eg:return C.c1()+M.m2();
//为了方便理解,我在下面重写了一遍
很好理解
#include<bits/stdc++.h>
using namespace std;
class Mouse; //这里先声明Mouse类,因为Cat类里面友元函数要使用
class Cat
{
private:
int w1;
public:
Cat(int w1)
{
this->w1=w1;
}
int c1()
{
return w1; //返回w1的值得函数
}
friend int totalWeight(Cat C,Mouse M);
};
class Mouse
{
private:
int w2;
public:
Mouse(int w2)
{
this->w2=w2;
}
int m2() //返回w2的值得函数
{
return w2;
}
friend int totalWeight(Cat C,Mouse M); //友元函数的作用就是在类外面,但是可以访问类的私有成员
};
int totalWeight(Cat C,Mouse M)
{
return C.c1()+M.m2();
}
主函数也分析一波吧
#include <iostream>
using namespace std;
/* 请在这里填写答案 */
int main()
{
int w1,w2;
cin>>w1>>w2; //输入两个重量
Cat tom(w1); //定义一个名为tom的Cat类,且把主函数的w1传到Cat类里面
Mouse jerry(w2); //这也一样
cout<<totalWeight(tom,jerry)<<endl; //注意,tom和jerry是Cat和Mouse类的类型,所以写友元函数时是(Cat C,Mouse M)
}