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

图片说明

#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个回答

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;
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐