谁帮忙看一下,这个错在哪

来源:百度知道 编辑:UC知道 时间:2024/07/05 19:50:45
#include<iostream.h>
class C0
{
public:
/********found********/
friend void fun(C0&,int,int );
void print()
{
/********found********/
cout<<"a="<<a<<",b="<<b<<endl;
}
private:
int a,b;
};
void fun(C0& obj,int t)
{
obj.a = t;
obj.b = 0;
}
void fun(C0& obj,int t,int j)
{
obj.a = t;
obj.b = j;
}
void main()
{
/********found********/
C0 obj;
fun(obj,5);
obj.print();
fun(obj,5,6);
obj.print();
}
只能改****found****下面那一条语句

a和b是类的私有变量
友元函数可以通过类对象访问对象的私有成员
所以,fun(obj,5); 这里就会报错的

class C0
{
public:
/********found********/
friend void fun(C0&,int,int );
void print()
{
/********found********/
cout<<"a="<<a<<",b="<<b<<endl;
}

void Seta(int x)
{
a = x;
}

void Setb(int y)
{
b = y;
}

private:
int a,b;
};

void fun(C0& obj,int t)
{
obj.Seta(t);
obj.Setb(0);
}
void fun(C0& obj,int t,int j)
{
obj.Seta(t);
obj.Setb(j);
}

void main()
{
/********found********/
C0 obj;
fun(obj,5);
obj.print();
fun(obj,5,6);
obj.print();
}

fun函数有问题
类CO的私有成员不能在类外访问


private:
int a,b;

该为:
pulic:
int a,b;

你必须把函数
void fun(C0&,int );
也声明为友元
friend