6-16 猫和老鼠有多重分数 30

定义猫和老鼠: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) 
}

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值