C++ 中的成员函数作为另一个类的友元
在这个程序中定义了一个实数类,和一个复数类。通过利用友元实现复数类的实部和实数类进行比较大小可能程序本身并无实际意义,但是为了学习这种方法。
//Real.h
#ifndefREAL
#define REAL
#include "Complex.h"
class Real{
public:
Real(int);
int getReal();
friend void Complex::convert(const Real &s);
private:
int a;
};
#endif
//Real.cpp
#include "Real.h"
Real::Real(int i)
:a(i)
{}
int Real::getReal()
{
return a;
}
//Complex.h
#ifndef COMPLEX
#define COMPLEX
class Complex{
public:
class Real;
Complex(int i,int j=0);
void convert(const Real &);
private:
int real;
int image;
};
#endif
//Complex.cpp
#include "Complex.h"
#include "Real.h"
#include <iostream.h>
Complex::Complex(int i,int j)
:real(i),image(j)
{}
void Complex::convert(const Real &x)
{
if (real > x.getReal())
cout<<"The complex is larger.\n";
cout<<"The real is larger.\n";
}
//Complex.h
#ifndef COMPLEX
#define COMPLEX
class Real;
class Complex{
public:
Complex(int i,int j=0);
void convert(const Real &);
private:
int real;
int image;
};
#endif
class Real;
class Complex{
public:
Complex(int i,int j=0);
void convert(Real &);
private:
int real;
int image;
};
class Real{
public:
Real(int);
int getReal();
friend void Complex::convert(Real &s);
private:
int a;
};
Real::Real(int i)
:a(i)
{}
int Real::getReal()
{
return a;
}
Complex::Complex(int i,int j)
:real(i),image(j)
{}
void Complex::convert(Real &x)
{
if (real > x.getReal())
cout<<"The complex is larger.\n";
cout<<"The real is larger.\n";
}