C+语言程序设计 第6讲:数组、指针与字符串
C++语言程序设计 第6讲: 数组、指针与字符串
友元 friend 癱友元是C+提供的一种破坏数据封装和数 据隐藏的机制。 通过将一个模块声明为另一个模块的友元, 个模块能够引用到另一个模块中本是被 隐藏的信息。 可以使用友元函数和友元类 癱为了确保数据的完整性,及数据封装与隐 藏的原则,建议尽量不使用或少使用友元
友元 friend 友元是C++提供的一种破坏数据封装和数 据隐藏的机制。 通过将一个模块声明为另一个模块的友元, 一个模块能够引用到另一个模块中本是被 隐藏的信息。 可以使用友元函数和友元类。 为了确保数据的完整性,及数据封装与隐 藏的原则,建议尽量不使用或少使用友元
例5-6:使用友元函数计算两点距离 a1 ass point// Point类声明 public //外部接口 Point(int xx=o, int yy=o)X=xx; Y=yy i b nt Getxoi return xi int Gety( return Y, I friend float fDist (Point &a, point &b) private //私有数据成员 int Xy float fDi int main() double d i point myp(1 of, 1. 0f), myp2 (4. 0f, 5. 0f) double cout<<The distance is i re七urn cout<< fDist (mypl, myp2) << endli return 0:
例5-6: 使用友元函数计算两点距离 class Point //Point类声明 { public: //外部接口 Point(int xx=0, int yy=0) {X=xx;Y=yy;} int GetX() { return X; } int GetY() { return Y; } friend float fDist (Point &a, Point &b); private: //私有数据成员 int X,Y; }; float fDist ( Point& a, Point& b ) { double dx = a.X-b.X; double dy = a.Y-b.Y; return (float)sqrt(dx*dx+dy*dy); } int main() { Point myp1(1.0f, 1.0f), myp2(4.0f, 5.0f); cout<<"The distance is “; cout<< fDist (myp1, myp2) << endl; return 0; }
友元类 class A friend class B void B: Set(int i) public void Display cout < x < endl F private Int xi 访问A的私有成员 class B ⅴoidB:: Display() I public void Set(int i) void Display() a Display ()i private: aa 但在A中不能访问B的私有成员
友元类 class A { friend class B; public: void Display() { cout << x << endl; } private: int x; } class B { public: void Set(int i); void Display(); private: A a; }; void B::Set(int i) { a.x = i; } void B::Display() { a.Display(); } 访问A的私有成员 但在 A 中不能访问 B 的私有成员。!!!
常类型 const 常类型是只读的意思 癱常类型的对象必须进行初始化,而且不能 被更新 癱常引用:被引用的对象不能被更新 const类型说明符&引用名 常对象:必须进行初始化,不能被更新 类名 cons t对象名
常类型 const 常类型是只读的意思。 常类型的对象必须进行初始化,而且不能 被更新。 常引用:被引用的对象不能被更新。 const 类型说明符 &引用名 常对象:必须进行初始化,不能被更新。 类名 const 对象名