C++ 简单的友元函数?

来源:百度知道 编辑:UC知道 时间:2024/05/13 19:24:42
要求:定义Boat与Car两各类,二者都有weight属性,定义二者的一个友元函数totalWeight()为外部函数,计算二者的重量和。
我的函数:
#include<iostream>
using namespace std;
class CBoat
{
public:
CBoat()
{
weight = 0;
}
CBoat(float x)
{
weight = x;
}
friend float totalWeight(CBoat &one);
float weight;
};
class CCar
{
CCar()
{
weight = 0;
}
CCar(float x)
{
weight = x;
}
friend float totalWeight(CCar &two);
float weight;
};
float weight;
float totalWeight(CBoat &one, CCar &two)
{
weight = CBoat.weight+CCar.weight;
return weight;
}

void main()
{
CBoat one(20);
CCar two(10);
cout<<totalWeight(CBoat &one, CCar &two)<<endl;
}

错误:
33:error C2275: 'CBoat' : illegal use of this type as an
expression
see declaration of 'CBoat'
CCar类的也是类似的错误

#include<iostream>
using namespace std;
class CBoat
{
public:
CBoat()
{
weight = 0;
}
CBoat(float x)
{
weight = x;
}
float weight;
};
class CCar
{
CCar()
{
weight = 0;
}
CCar(float x)
{
weight = x;
}

float weight;
};
float weight;
float totalWeight(CBoat &one, CCar &two)
{
weight = one.weight+two.weight;
return weight;
}

void main()
{
CBoat one(20);
CCar two(10);
cout<<totalWeight(&one, &two)<<endl;
}

你试一下,不行的话给我QQ 442853042