qq_45735316 2020-04-03 10:36 采纳率: 94.1%
浏览 228
已采纳

这怎么搞?将类的定义放在另一个头文件吗?

图片说明

#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
//C++ P186 5-14
/*定义Boat与Car两个类,二者都有weight属性,定义两者的一个友元函数
getTatalWweigth(),计算两者的重量和*/
class Boat{
    public:
        Boat(int weight=0):weight(weight){}       //构造函数 
        friend float getTotalWeight(Boat &b,Car &c); //友元函数 
    private:
        float weight;
}; 
class Car{
    public:
        Car(int weight=0):weight(weight){}       //构造函数 
        friend float getTotalWeight(Boat &b,Car &c);   //友元函数 
    private:
        float weight;
};
float getTotalWeight(Boat &b,Car &c)
{
    return (b.weight+c.weight);
}

int main(int argc, char** argv) {
    Boat b(10);
    Car c(20);
    cout<<"Total Weight=";
    cout<<getTotalWeight(b,c)<<endl;
    return 0;
}
  • 写回答

1条回答

  • 小学狗喵喵叫 2020-04-03 11:07
    关注
    class Car;
    class Boat {
    public:
        Boat(int weight = 0) :weight(weight) {}       //构造函数 
        friend float getTotalWeight(Boat& b, Car& c); //友元函数 
    private:
        float weight;
    };
    class Car {
    public:
        Car(int weight = 0) :weight(weight) {}       //构造函数 
        friend float getTotalWeight(Boat& b, Car& c);   //友元函数 
    private:
        float weight;
    };
    float getTotalWeight(Boat& b, Car& c);
    
    #include "....h"
    float getTotalWeight(Boat& b, Car& c)
    {
        return (b.weight + c.weight);
    }
    
    #include "....h"
    #include <iostream>
    using namespace std;
    int main(int argc, char** argv) {
        Boat b(10);
        Car c(20);
        cout<<"Total Weight=";
        cout<<getTotalWeight(b,c)<<endl;
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示