ƵĿ
ҳ > 򿪷 > > C++ >
ΪʲôҪʹõԪ
2017-10-11 09:21:55         Դsyemingıר  
ղ   ҪͶ

ʲô»õԪԪʲôԪͨԱⶼC++еһЩպάĿĿ档Ҫdz̸һC++еԪв©֮ѼʱָһĽ
һ
Ԫʵ֮ݹʱԼϵͳЧʡ磺AеĺҪBеijԱôAиúҪBԪ
Ԫȥ˽бͱӶʹ๲ͬһ

ʹó
ʵһЩʵҲҪʵ֣ͨΪԪ
һлõԪ
1صijЩҪʹԪ
2Ҫݵʱ

ȱ
1ŵ㣺ܹЧʣ򵥣
2ȱ㣺ƻķװҪʹóԱDzѲʹԪ

ġʹ˵
1Ԫ⺯Է˽л߹УҶû
2ֱӵԪҪָͨ룻
3Ԫûthisָ룬Ҳܱ̳У
4Ԫʽ friend + ͨ

塢˵
1֪֮꣬ľ

#include 
#include 

using namespace std;

class Point
{
public:
    Point(double xx, double yy)
    {
        x = xx;
        y = yy;
    }
    void GetXY();
    friend double Distance(Point &a, Point &b);
protected:
private:
    double x, y;
};
void Point::GetXY()
{
    cout << "(" << x << "," << y << ")" << endl;
}

double Distance(Point &a, Point &b)
{
    double length;
    length = sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y));     //е˽гԱ
    return length;
}

void main(void)
{
    Point p1(3.0, 4.0), p2(6.0, 8.0);
    p1.GetXY();    //Աĵ÷ͨʹö
    p2.GetXY();
    double d = Distance(p1, p2);     //Ԫĵ÷ͬͨĵһҪԱ
    cout << "distance=" << d << endl;
    return;
}

н
дͼƬ


ڸóеPoint˵һԪDistance()˵ʱǰ߼friendؼ֣ʶdzԱԪĶ巽ͨһͬڳԱĶ壬ΪҪָࡣǣе˽гԱеa.xb.xa.yb.y˽гԱͨõġڵԪʱҲͬͨĵһҪԱáУp1.Getxy()p2.Getxy()dzԱĵãҪöʾDistance(p1, p2)ԪĵãֱӵãҪʾIJǶ

2أҪõԪ

#include 
#include 
using namespace std;

class Point
{
public:
    Point(double xx, double yy)
    {
        x = xx;
        y = yy;
    }
    void GetXY();
    friend double Distance(Point &a, Point &b);
    friend ostream &operator <<(ostream &out, Point &b);
protected:
private:
    double x, y;
};

ostream &operator <<(ostream &out, Point &b)
{
    out << "(" << b.x << "," << b.y << ")" << endl;
    return out;
}
void Point::GetXY()
{
    //cout<<"("<x<<","<y<<")"<н

3ͨԪԪӡ˽гԱ ֱһAB һ˽Աͨ캯ʼAһԱShow(B &b)ӡAB˽гԱֱͨԪԪʵִ˹ܡ

#include 
using namespace std;

class B
{
private:
    int tt;
    friend class A;
    friend void Show(A&, B&);
public:
    B(int tempB = 100) :tt(tempB) {}//default constructor
};

class A
{
private:
    int value;
    friend void Show(A&, B&);
public:
    A(int tempA = 200) :value(tempA) {}//default constructor
    void Show(B &b)
    {
        cout << "class A memeber function" << endl;
        cout << "class A private variable value:" << value << endl;
        cout << "class B private variable value:" << b.tt << endl;
        cout << endl;
    }
};

void Show(A& a, B& b)
{
    cout << "friend function" << endl;
    cout << "class A private variable value:" << a.value << endl;
    cout << "class B private variable value:" << b.tt << endl;
}

void main()
{
    A a;
    B b;
    a.Show(b);
    Show(a, b);

    return;
}

ᵽĬϹ캯

ѷ!رվҳ
һƪSTM32F4 FPUм
һƪunionһֽʡռͳԱ
ͼƼ

| ϵ | | Ͷʺ | Ȩ | ߰ | վͼ | Ʒ | Vipѵ | ٱ

Ȩ: --ʵõITѧϰվ