#include <iostream>
using namespace std;
class Screen; //需要先声明Screen因为在Dog中引用了
class Dog //这里的Dog必须在Screen前定义,因为在类的内部声明了Dog类内部的成员函数为友元,
//但函数的实现必须要在Screen类内部,因为函数内部操作了Screen的内部成员
{
public:
int foo(Screen& screen);
int koo(Screen& screen);
};
class Screen
{
public:
typedef std::string::size_type index;
Screen(index ht=0,index wd=0):contents(ht*wd,' '),cursor(0),height(ht),width(wd)
{}
int area() const
{
return height * width;
}
//声明友元函数
friend int calcArea(Screen&);
//声明友元类
friend class Window_Mar;
//friend class Dog;
//声明类内部的友元函数
friend int Dog::foo(Screen&);
private:
std::string contents;
index cursor;
index height, width;
};
int Dog::foo(Screen & screen)
{
return screen.height * screen.width;
}
//koo为非友元函数
//int Dog::koo(Screen& screen)
//{
// return screen.height * screen.width;
//}
//友元函数可以使用类内部的私有成员
int calcArea(Screen& screen)
{
return screen.height * screen.width;
}
//友元类
class Window_Mar //窗口管理位-对Screen进行管理
{
public:
void relocate(int r, int c, Screen& s)
{
s.height += r;
s.width += c;
}
};
int main()
{
Screen a(60, 100);
cout << a.area() << endl;
cout << calcArea(a) << endl;
Window_Mar wm;
wm.relocate(40, 100,a);
cout << calcArea(a) << endl;
Dog dog;
cout << dog.foo(a) << endl; //foo为友元函数
return 0;
}
C++-友元函数
于 2022-04-05 10:37:09 首次发布