#include<iostream>
using namespace std;
class Car;
class Boat
{
private:
int Boatwe;
public:
int Weight1()
{
return Boatwe=500;
}
friend totalWeight(int);
};
class Car
{
private:
int Carwe;
public:
int Weight2()
{
return Carwe=300;
}
friend totalWeight(int);
};
int totalWeight(int)
{
int x;
return x.Boat+x.Car;
}
main()
{
cout>>"总重量为">>totalWeight()>>endl;
}
可以给我改改吗?最好详细解释一下~~构造函数学的超级不好~~
知道上有其他解答的,看不懂,请勿复制粘贴~
float totalWeight(boat a,car b); 这个函数名 跟类名重复了 而且他的两个参数是类类型的 但是在编译。
改成 m_totalWeight;
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
class car;
class boat{
float weight;
public:
boat(float a){
weight=a;
}
friend float y_totalWeight(boat a,car b);
};
class car{
float weight;
public:
car(float b){
weight=b;
}
friend float y_totalWeight(boat a,car b);
};
class totalWeight{
float m_totalWeight;
public:
void tot(float x,float y){
car a(x);
boat b(y);
m_totalWeight=x+y;
}
void output(){
cout<<"totalWeight= "<<m_totalWeight<<endl;
}
};
float y_totalWeight(boat a,car b);
int main(){
totalWeight t;
t.tot(1,2);
t.output();
system("pause");
}
扩展资料:
条款21: 尽可能使用const。
条款22: 尽量用“传引用”而不用“传值”。
条款23: 必须返回一个对象时不要试图返回一个引用。
可以很容易地对有理数进行乘法操作:
rational oneeighth(1,8);
rational onehalf(1,2);
rational result = onehalf * oneeighth; // 运行良好。
result = result * oneeighth; // 运行良好。
但不要满足,还要支持混合类型操作,比如,rational要能和int相乘。但当写下下面的代码时,只有一半工作:
result = onehalf * 2; // 运行良好。
result = 2 * onehalf; // 出错!
这是一个不好的苗头。记得吗?乘法要满足交换律。
如果用下面的等价函数形式重写上面的两个例子,问题的原因就很明显了:
result = onehalf.operator*⑵; // 运行良好。
参考资料来源:百度百科-友元函数