读书人

C++ 中的成员函数作为另一个种的友元

发布时间: 2012-12-31 11:57:51 作者: rapoo

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";
}

在VC++中编译complex.cpp总是显示错误,error C2027: use of undefined type 'Real'
Real明明是定义了,怎么说没定义呢? 我知道怎么改可以通过,但是我想知道这里是怎么错了。
[解决办法]
Complex.h 改成这样就好了。

//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; 写在类里面的时候声明 Complex::Real,和 ::Real 不是一个东西,convert 实现的时候,编译器认为其参数是 Complex::Real,然后这个又没有定义所以就报错。放在外面以后 class Real; 就声明 ::Real 了。
顺便说一句,别再 #include <iostream.h> 了,#include <iostream> 吧,好编译器都不认 iostream.h 的。
[解决办法]
整个的程序流程是这样的:
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";
}

读书人网 >C++

热点推荐