有一道C++6.0题,要求用友元函数,可以计算船和汽车总质量,下面这个程序有错吗?错在哪里了

#include<iostream>
using namespace std;
class Boat;
class Car{
public:Car(int c){Cweight=c;}
friend int getTotalweight(Car&Cweight,Boat&Bweight);
private:int c;
};
class Boat{
public:Boat(int b){Bweight=b;}
friend int getTotelweight(Car&Cweight,Boat&Bweight);
private:int b;
};
int getTotalweight(Car&Cweight,Boat&Bweight)
{return Cweight.c+Bweight.b;}
int main(){
int x,y;
Car Cweight(x);
Boat Bweight(y);
cout<<"输入Car和Boat的重量"<<endl;
cin>>x>>y;
cout<<"它们的总重量是"<<getTotalweight(Cweight,Bweight)<<endl;
return 0;
}

#include<iostream>
using namespace std;
class Boat;
class Car{
    public:
        Car(int Cweight){c=Cweight;} //c才是成员变量
        friend int getTotalweight(Car & Cweight,Boat & Bweight);
    private:
            int c; 
};
class Boat{
    public:
        Boat(int Bweight){b=Bweight;} //b才是成员变量
        friend int getTotalweight(Car & Cweight,Boat & Bweight); //函数名写错了
    private:
        int b;
};
int getTotalweight(Car&Cweight,Boat&Bweight)
{
    return    Cweight.c+Bweight.b;
}
int main(){
    int x,y;
    cout<<"输入Car和Boat的重量"<<endl;
    cin>>x>>y; //先输入,后定义

    Car Cweight(x);
    Boat Bweight(y);
    cout<<"它们的总重量是"<<getTotalweight(Cweight,Bweight)<<endl;
    return 0;
}

追问

如果构造Car和Boat两个类时,将Cweight与Bweght作为形参,那两个类的私有成员中不需要定义Cweight和Bweight吗?

追答

形参只是一个数据的“形式描述”!
当调用函数时,系统会用实参来替换形参的!
函数讲的是一种方法,形参是在这个方法中的可变的应用对象,在实际调用时,才会有数值,就相当于公式f(x)中的x

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-12-06
#include<iostream>
using namespace std;
class Boat;
class Car {
public:Car(int c) { this->c = c; }
    friend int getTotalweight(Car&Cweight, Boat&Bweight);
private:int c;
};
class Boat {
public:Boat(int b) { this->b = b; }
    friend int getTotalweight(Car&Cweight, Boat&Bweight);
private:int b;
};
int getTotalweight(Car&Cweight, Boat&Bweight)
{
 return    Cweight.c + Bweight.b;
}
int main() {
 int x, y;
 cout << "输入Car和Boat的重量" << endl;
 cin >> x >> y;

 Car Cweight(x);
 Boat Bweight(y);
 cout << "它们的总重量是" << getTotalweight(Cweight, Bweight) << endl;
 return 0;
}

本回答被网友采纳
相似回答