C++PTA:6-1 车与船的重量 (20 分)

定义一boat与car两个类,二者都有weight属性,定义二者的一个友元函数totalweight(),计算二者的重量和。
测试程序样例:

//在这里给出函数被调用进行测试的例子。例如:
#include <iostream>
using namespace std;

/* 请在这里填写答案 */

int main()
{
  int c,b;
  cin>>c>>b;
  car c1(c);
  boat b1(b);
  cout<<totalweight(b1,c1)<<endl;
}

输入样例:
1000 2000
输出样例:
3000
【代码】

class car;   //向前引用声明 
class boat{
 private:
  int weight;
 public:
  boat(int weight=0){   //构造函数 
   this->weight=weight;
  }
  int GetW(){
   return weight;
  }
  friend int totalweight(boat &b1,car &c1);  //友元函数的声明 
};
class car{
 private:
  int weight;
 public:
  car(int weight=0){
   this->weight=weight;
  }
  int GetW(){
   return weight;
  }
  friend int totalweight(boat &b1,car &c1);
};
 int totalweight(boat &b1,car &c1){   
 return c1.GetW()+b1.GetW();
}

//在写友元函数的定义的时候,不用再写friend,会报错

发布了31 篇原创文章 · 获赞 2 · 访问量 3829

猜你喜欢

转载自blog.csdn.net/weixin_44652687/article/details/101981410