将友谊授予来自不同标头中定义的类的函数
Granting friendship to a function from a class defined in a different header
首先,这不是"家庭作业",这是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.h
和thirdclass.h
,因此应该完全跳过相应的正向声明。
然而,在thirdclass.h
中,您不需要firstclass.h
:您声明的是指向firstclass
的指针,而不是使用其成员,因此不需要include。
一般规则是,如果您只需要一个指针,就应该转发声明您的类,并在您需要了解类的成员时包括它们的头。
删除包含在thirdclass.h中的firstclass.h。这会导致在第三类之前定义firstclass。小心递归包含。
要查看类的实际定义时间(取决于编译器),请在实际的类定义之前添加#pragma消息。
相关文章:
- 在命名空间中定义函数还是限定函数
- 为什么在定义函数之前先声明它
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- 这个c++代码是如何在没有定义函数的情况下运行的
- 具有外部"c"和程序集的未定义函数
- 已定义函数时出现 G++ "未定义的引用"错误
- 将自定义函数传递到基抽象类中以延迟执行
- C++使用 rand 定义函数语法
- Arduino:在 loop() 和自定义函数中运行相同的代码时出现问题
- 将具有固定签名的自定义函数名称注入 CRTP
- 使用定义函数模板别名
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 在内联程序集中定义函数和从 C++ 调用时出现问题
- 在 Metal 着色器代码中,如何定义函数的 in/out 参数变量?
- 声明和定义函数静态会产生"undefined reference to function_name()"
- 朋友定义函数的名称空间是什么
- 介子 对用户定义函数的未定义引用
- 如何使用 "using" 关键字定义函数原型/签名
- 在 C 结构中定义C++函数