练习友元类和友元函数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了练习友元类和友元函数相关的知识,希望对你有一定的参考价值。

#include <iostream>
using namespace std;
class Circle;
class Point
{
private:
    float x;
    float y;
public:
    Point();
    Point(float a,float b);
    friend class Circle;
    friend const Point middle(const Point &u,const Point &v);
    void print()const;
};
Point::Point():x(0.0),y(0.0)
{
    cout << "Defalt constraction is called " << endl;
}
Point::Point(float a,float b):x(a),y(b){}
void Point::print()const
{
    cout << " x: " << x << " y " << y <<endl;
}
const Point middle (const Point &u,const Point &v )
{
    return Point ((u.x+v.x)/2.0,(u.y+v.y)/2.0);
}
class Circle
{
private:
    float radius;
    Point center;
public:
    Circle();
    Circle& move(float a,float b);
    void print()const;
};
Circle::Circle():radius(0.0)
{
    center.x = 0.0;
    center.y = 0.0;
}

Circle&Circle::move(float a,float b)
{
    center.x += a;
    center.y += b;
    return *this;
}
void Circle::print()const
{
    center.print();
    cout << "radius: " << radius <<endl;
}
int main()
{
    Point p1(1.0,2.0);
    Point p2(3.0,4.0);
    p1.print();
    p2.print();
    cout << "the diffrence between the two point is:" << endl;
    middle(p1,p2).print();
    Circle c;
    c.print();
    cout << "move the center:"<< endl;
    c.move(10.0,10.0);
    c.print();
    cout << "Hello World!" << endl;
    return 0;
}

 

以上是关于练习友元类和友元函数的主要内容,如果未能解决你的问题,请参考以下文章

友元函数和友元类

友元函数和友元类

类和对象——补充(运算符重载,static和explicit关键字和友元,内部类)

什么是友元?为什么要引入友元?解释友元函数和友元类

友元函数都有哪些特点?

友元函数友元类.