【问题标题】:Granting friendship to a function from a class defined in a different header从不同标头中定义的类中为函数授予友谊
【发布时间】:2012-08-05 11:11:01
【问题描述】:

首先,这不是“作业”,它是 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

【问题讨论】:

    标签: c++


    【解决方案1】:

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

    但是,在thirdclass.h 中,您不需要firstclass.h:您声明了一个指向firstclass 的指针,而不是使用它的成员,因此您不需要包含。

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

    【讨论】:

    • 没那么简单。他将 firstclass.h 包含在 thirdclass.h 中。递归包含是问题的一部分。
    • @walrii 没关系,因为 OP 的包含警卫做得正确。
    • 包含守卫也隐藏了问题。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-09
      • 2021-08-09
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-30
      相关资源
      最近更新 更多