标题:一个小问题
取消只看楼主
hellodudu
Rank: 1
等 级:新手上路
帖 子:5
专家分:0
注 册:2006-7-2
 问题点数:0 回复次数:4 
一个小问题

#include<iostream>
using namespace std;
class Boat
{
public:
Boat(int w=0) {weight=w;}
void coutB() {cout<<"Boat weight="<<weight<<endl;}
friend void totalWeight(); //定义totalweight为boat的友元函数
private:
int weight;
};

class Car
{
Car(int w=0) {weight=w;}
void coutB() {cout<<"Car weight="<<weight<<endl;}
friend void totalWeight(); //定义totalweight为car的友元函数
private:
int weight;
};

void totalWeight()
{
int B,C;
B=boat.weight;
C=car.weight; //通过对象访问其weight
cout<<"total weight="<<B+C<<endl;
}

void main()
{
Boat boat(120);
Car car(110); //生成对象
totalWeight();
}

实现功能:totalweight计算两者的重量之和
编译报错:error C2065: 'boat' : undeclared identifier
error C2228: left of '.weight' must have class/struct/union type
error C2065: 'car' : undeclared identifier
error C2228: left of '.weight' must have class/struct/union type
error C2248: 'Car::Car' : cannot access private member declared in class 'Car'
see declaration of 'Car::Car'



请高手帮忙!!1
谢谢先~

搜索更多相关主题的帖子: weight void Boat int Car 
2006-10-03 18:59
hellodudu
Rank: 1
等 级:新手上路
帖 子:5
专家分:0
注 册:2006-7-2
得分:0 

小写的car和boat是对象啊~
我还是看不出来哪的问题!

2006-10-03 19:17
hellodudu
Rank: 1
等 级:新手上路
帖 子:5
专家分:0
注 册:2006-7-2
得分:0 
但我定义的只是一个友元函数totalWeight.友元函数可以通过对象访问私有数据的吧.
2006-10-03 19:46
hellodudu
Rank: 1
等 级:新手上路
帖 子:5
专家分:0
注 册:2006-7-2
得分:0 
我试试
2006-10-03 19:59
hellodudu
Rank: 1
等 级:新手上路
帖 子:5
专家分:0
注 册:2006-7-2
得分:0 

我改了,还是不行
我刚开始学,对这方面的语法还不太熟,能请你说的详细点吗?

#include<iostream>
using namespace std;
class Boat
{
public:
Boat(int w=0) {weight=w;}
void coutB() {cout<<"Boat weight="<<weight<<endl;}
friend void totalWeight(Boat &a,Car &b); //定义totalweight为boat的友元函数
private:
int weight;
};

class Car
{
Car(int w=0) {weight=w;}
void coutB() {cout<<"Car weight="<<weight<<endl;}
friend void totalWeight(Boat &a,Car &b); //定义totalweight为car的友元函数
private:
int weight;
};

void totalWeight(Boat &p1,Car &p2)
{
int x,y;
x=p1.weight;
y=p2.weight; //通过对象访问其weight
cout<<"total weight="<<x+y<<endl;
}

void main()
{
Boat boat(120);
Car car(110); //生成对象
totalWeight(boat,car);
}

还有一个问题,就是友元函数对类的访问只能通过参数传递吗?

2006-10-03 20:27



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-94098-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.343763 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved