#include <iostream> #include <cmath> using namespace std; class Point { private: double x, y; //___________; //阅读程序发现该有的构造函数成员变量成员函数都有了,与他相关联的类Line中定义了成员函数GetLength(),其中访问了Point的私有变量x和y。这表明GetLength()是Point的友元函数。重点来了:将一个类的成员函数声明为另一个类的友元函数需要有向前引用声明的内容 friend class Line; public: Point(double i = 0, double j = 0) { x = i; y = j; } Point(Point& p) { x = p.x; y = p.y; } }; class Line { private: Point p1, p2; public: Line(Point& xp1,Point& xp2) :p1(xp1),p2(xp2){} //Line(Point& xp1.Point& xp2) :_____{} //第二个空这个空在类的构造函数中回归构造函数声明的多种方式会发现,种类虽然多本质都是为构造函数赋初值的地方所以缺的地方为赋初值 //另外类Point中定义了复制构造函数Pint(Point &p),可以用来对p1,p2初始化,所以这个空要填写的是 p1(xp1),p2(xp2) double GetLength(); }; double Line::GetLength() { double dx = p2.x - p1.x; double dy = p2.y - p1.y; return sqrt(dx * dx + dy * dy); } int main() { Point p1, p2(6, 8); Line L1(p1, p2); cout << L1.GetLength() << endl; }
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。