将友谊授予来自不同标头中定义的类的函数

Granting friendship to a function from a class defined in a different header

本文关键字:定义 函数 友谊      更新时间:2023-10-16

首先,这不是"家庭作业",这是C++第1卷第5章第5行中的一个问题。我需要制作3个类,第一个类将其内部的友谊授予整个第二个类,而友谊仅授予第三个类中的一个函数。

我对将友谊授予整个第二类没有问题,但对授予第三类函数没有问题,如果我在同一个头中声明第三类,就没有问题。但在不同的头中,我得到了一些未定义的类型/声明。感谢您的帮助,这里是代码:

#ifndef FIRSTCLASS_H
#define FIRSTCLASS_H
//firstclasss header file
#include "secondclass.h"
#include "thirdclass.h"
class secondclass; //dummy declaration so it can share friendship
class thirdclass;  //it doesnt work when i want to give friendship to a function
class firstclass{
private:
    int a;
    int b;
public:
    friend secondclass; //granting friendship to the whole class
    friend void thirdclass::z(firstclass *); //error
    //use of undefined type 'thirdclass'
    //see declaration of 'thirdclass'
};
#endif FIRSTCLASS_H

#ifndef THIRDCLASS_H
#define THIRDCLASS_H
//thirdclass header file
#include "firstclass.h"
class firstclass;
class thirdclass{
public:
    void z(firstclass *);
};
#endif THIRDCLASS_H

只有在不包含相应类的头时,才需要提供正向声明。由于已经包含了secondclass.hthirdclass.h,因此应该完全跳过相应的正向声明。

然而,在thirdclass.h中,您不需要firstclass.h:您声明的是指向firstclass的指针,而不是使用其成员,因此不需要include。

一般规则是,如果您只需要一个指针,就应该转发声明您的类,并在您需要了解类的成员时包括它们的头。

删除包含在thirdclass.h中的firstclass.h。这会导致在第三类之前定义firstclass。小心递归包含。

要查看类的实际定义时间(取决于编译器),请在实际的类定义之前添加#pragma消息。