C++简单程序出错,望高手解答

来源:百度知道 编辑:UC知道 时间:2024/06/17 03:29:12
#include <iostream>
using namespace std;
class Car;
class Boat
{
public:
Boat(double w)
{
weight=w;
}
double GetWeight()
{
return weight;
}
friend double totalWeight(Car &c,Boat &b);
private:
double weight;
};

class Car
{
public:
Car(double w)
{
weight=w;
}
double GetWeight()
{
return weight;
}
friend double totalWeight(Car &c,Boat &b);
private:
double weight;
};

double totalWeight(Car &c,Boat &b)
{
return c.weight+b.weight;
}

void main()
{
Boat b(40);
Car c(30);
cout<<totalWeight(b,c)<<endl;
}

cout<<totalWeight(b,c)<<endl;这句出错
'totalWeight' : cannot convert parameter 1 from 'class Boat' to 'class Car &'
A reference that is not to 'const' cannot

呵呵,粗心了吧
main函数中:
cout<<totalWeight(b,c)<<endl;
改为:
cout<<totalWeight(c,b)<<endl;

就是你引用对象的类型不对.

Boat类型对应Boat类型

Car类型对应Car类型

#include <iostream>
using namespace std;
class Car;
class Boat
{
public:
Boat(double w)
{
weight=w;
}
double GetWeight()
{
return weight;
}
friend double totalWeight(Car &c,Boat &b);
private:
double weight;
};

class Car
{
public:
Car(double w)
{
weight=w;
}
double GetWeight()
{
return weight;
}
friend double totalWeight(Car &c,Boat &b);
private:
double weight;
};

double totalWeight(Car &c,Boat &b)
{
return c.weight+b.weight;
}

void main()
{
Boat b(40);
Car c(30);
cout<<totalWeight(c,b)<<endl;
}