怎么使用友元函数?
答案:1 悬赏:0 手机版
解决时间 2021-01-23 16:35
- 提问者网友:不爱我么
- 2021-01-23 13:18
请写一个用友元函数求矩形周长和面积的实例。谢谢
最佳答案
- 五星知识达人网友:痴妹与他
- 2021-01-23 14:56
友元函数可以访问类的对象的私有成员变量,成员函数,代码如下:
class TestClass
{
private:
int length;
int width;
public:
TestClass(int len,int wide){ length=len; width=wide;};
friend int CaculateArea(TestClass test); //注意要加关键字friend
friend int CaculateCircle(TestClass test);
};
int CaculateArea(TestClass test) //友元函数可以访问test对象的私有成员变量length,width
{
return test.length * test.width;
}
int CaculateCircle(TestClass test)
{
return 2*(test.length + test.width);
}
int main()
{
TestClass testClass(2,3);
cout<<CaculateArea(testClass)<<endl;
cout<<CaculateCircle(testClass)<<endl;
return 0;
}
class TestClass
{
private:
int length;
int width;
public:
TestClass(int len,int wide){ length=len; width=wide;};
friend int CaculateArea(TestClass test); //注意要加关键字friend
friend int CaculateCircle(TestClass test);
};
int CaculateArea(TestClass test) //友元函数可以访问test对象的私有成员变量length,width
{
return test.length * test.width;
}
int CaculateCircle(TestClass test)
{
return 2*(test.length + test.width);
}
int main()
{
TestClass testClass(2,3);
cout<<CaculateArea(testClass)<<endl;
cout<<CaculateCircle(testClass)<<endl;
return 0;
}
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯