向不同标头中定义的类中的函数授予友谊

2024-02-14

首先,这不是“家庭作业”,它是 Thinking in C++ Vol 1, Chapter 5 ex 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.h and thirdclass.h您应该完全跳过相应的前向声明。

In the thirdclass.h,但是,您不需要firstclass.h: 你正在声明一个指向firstclass,不使用其成员,因此您不需要包含。

一般规则是,如果您需要的只是一个指针,则应该前向声明您的类;如果您需要了解类的成员,则应包含它们的标头。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

向不同标头中定义的类中的函数授予友谊 的相关文章

随机推荐